create
으로 스토어 생성하기import { create } from 'zustand';
export const use이름Store = create((set, get) => {
return {
상태 : 초깃값,
액션: 함수
}
})
create함수는 스토어(store)를 생성하여 반환한다.
스토어는 상태와 그 상태를 조작하는 액션으로 이루어져 있다.
export const useCounterStore = create<{
count: number;
increase: () => void;
decrease: () => void;
}>((set, get) => ({
count: 0, // 상태와 상태의 초깃값
increase: () => {
const { count } = get(); // get함수는 상태와 액션을 가진 스토어를 가져올 수 있다.
set({ count: count + 1 }); // set함수를 호출( = 변경할 상태를 속성으로 포함한 객체를 전달)
},
decrease: () => {
// 혹은 콜백함수를 사용하면 state를 바로 가져올 수 있다.
set((state) => ({ count: state.count - 1 }));
},
}));
store의 타입정의를 state와 action으로 나누어서 작성한다음 &연산으로 합칠 수 있다.
type CounterState = {
count: number;
};
type CounterActions = {
increase: () => void;
decrease: () => void;
};
type CounterStore = CounterState & CounterActions;
export const useCounterStore = create<CounterStore>((set, get) => ({
(...)
'use client';
import { useCounterStore } from '@/stores/counter-store';
export default function Home() {
const count = useCounterStore((state) => state.count);
const increase = useCounterStore((state) => state.increase);
const decrease = useCounterStore((state) => state.decrease);
// 권장하지 않는 방법 : store 객체 자체를 얻기 -> 사용하지 않는 상태가 변경되어도 리랜더링이 일어남
// const store = useCounterStore();
return (
<div className=" min-h-screen p-8 pb-20 gap-16 sm:p-20 ">
hello
<button onClick={() => increase()}> increase</button>
<button onClick={() => decrease()}> decrease</button>
<div>{count}</div>
</div>
);
}
단일 스토어의 액션을 많이 사용하면, 액션만을 분리해서 관리하는 패턴을 활용할 수 있다.
바로 액션들을 actions라는 객체안에 담아서 관리하면 된다.
type CounterActions = {
actions: {
increase: () => void;
decrease: () => void;
};
};
export const useCounterStore = create<CounterStore>((set, get) => ({
count: 0, // 상태와 상태의 초깃값
actions: {
increase: () => {
set((state) => ({ count: state.count + 1 }));
},
decrease: () => {
set((state) => ({ count: state.count - 1 }));
},
},
}));
사용처에서는 다음과 같이 사용할 수 있다.
// 기존방식
const increase = useCounterStore((state) => state.increase);
const decrease = useCounterStore((state) => state.decrease);
// actions만 모은 객체를 내보낸 방식
const {increase, decrease} = useCounterStore((state) => state.actions);
https://www.heropy.dev/p/n74Tgc
https://zustand.docs.pmnd.rs/getting-started/introduction
https://zustand.docs.pmnd.rs/guides/nextjs