Zustand에서 권장되는 사용법은 스토어에 액션을 포함하는 것입니다. (상태 속성과 액션을 한 곳에서 관리)
import { create } from 'zustand';
export const useBoundStore = create((set) => ({
// 속성
count: 0,
text: 'hello',
// 액션
increament: () => set((state) => ({ count: state.count + 1 })),
setText: (text) => set(() => ({ text })),
}));
이렇게 하면 데이터 속성과 데이터를 업데이트 하는 액션이 함께 포함된 독립형 스토어가 생성됩니다.
다른 접근 방식은 모듈 수준에서 스토어 외부에 액션을 분리 정의하는 것입니다.
export const useBoundStore = (set) => ({
count; 0,
text: 'hello',
});
export const increment = () =>
useBoundStore.setState((state) => ({ count: state.count + 1 }));
export const setText = (text) =>
useBoundStore.setState(() => ({ text }));
이 방법은 몇 가지 장점이 있습니다.
※ 이 패턴은 별도의 단점을 제공하지는 않지만, 캡슐화 특성으로 인해 통합 관리하는 것을 권장합니다.