티스토리 뷰
요즘에 state library 뭐를 사용할까 하다가 redux 도 사용해보고 recoil 사용해보고 했는데
그 어떤것보다도 Flux 패턴과 유사해 러닝커브가 낮다고 생각해서
현재 가장 효율적으로 사용할 수 있는 zustand를 선택하게 되었다.
[zustand 설치방법]
npm install zustand
yarn add zustand
[type 부터 생성]
// src/types.ts
export interface TotalCount {
totalCount: number;
setTotalCount: (count: number) => void;
}
[store 를 생성하는 법]
// src/store.ts
import create from 'zustand';
import { devtools } from 'zustand/middleware';
import { TotalCount } from './types';
export const totalStore = create<TotalCount>()(
devtools((set) => ({
totalCount: 0,
setTotalCount: (count) => set({ totalCount: count }),
}), { name: 'mitreStore' })
);
[state selector 사용하는 법]
// src/components/Counter.tsx
import React from 'react';
import { totalStore } from '../store';
const Counter = () => {
const totalCount = totalStore((state) => state.totalCount);
const setTotalCount = totalStore((state) => state.setTotalCount);
return (
<div>
<h1>Count: {totalCount}</h1>
<button onClick={() => setTotalCount(totalCount + 1)}>Increase</button>
<button onClick={() => setTotalCount(totalCount - 1)}>Decrease</button>
<button onClick={() => setTotalCount(0)}>Reset</button>
</div>
);
};
export default Counter;
[비동기 작업관리 하는 법]
// src/store.ts
import create from 'zustand';
import { devtools } from 'zustand/middleware';
import { TotalCount } from './types';
interface TotalStore extends TotalCount {
loading: boolean;
getTotalCount: () => Promise<void>;
}
export const totalStore = create<TotalStore>()(
devtools((set) => ({
totalCount: 0,
loading: false,
setTotalCount: (count) => set({ totalCount: count }),
getTotalCount: async () => {
set({ loading: true });
try {
// 여기에 실제 API 호출 코드를 작성하기
const response = await fetch('/api/totalCount');
const data = await response.json();
set({ totalCount: data.count });
} catch (error) {
console.error('total count:', error);
} finally {
set({ loading: false });
}
},
}), { name: 'totalStore' })
);
[Immer 사용해서 상태관리하기]
// src/store.ts
import create from 'zustand';
import { devtools } from 'zustand/middleware';
import produce from 'immer';
import { TotalCount } from './types';
export const totalStore = create<TotalStore>()(
devtools((set) => ({
totalCount: 0,
loading: false,
setTotalCount: (count) => set(produce((state) => {
state.totalCount = count;
})),
fetchTotalCount: async () => {
set(produce((state) => {
state.loading = true;
}));
try {
// 여기에 실제 API 호출 코드를 작성하기!!
const response = await fetch('/api/totalCount');
const data = await response.json();
set(produce((state) => {
state.totalCount = data.count;
}));
} catch (error) {
console.error(' total count:', error);
} finally {
set(produce((state) => {
state.loading = false;
}));
}
},
}), { name: 'totalStore' })
);
댓글