# 설치
npm i zustand
src/store/useCountStore.ts
import { create } from 'zustand'
interface CountState {
count: number;
increasePopulation: () => void;
removeAll: () => void;
}
const useCountStore = create<CountState>(set => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
removeAll: () => set({ count: 0 }),
}))
export default useCountStore
src/pages/MainPage.tsx
import useCountStore from "../store/useCountStore";
function MainPage() {
const { count, increase, removeAll } = useCountStore((state) => state)
return (
<>
<h2>{count}</h2>
<button onClick={increase}>one up</button>
<button onClick={removeAll}>remove all</button>
</>
)
}
export default MainPage;
import { create, StateCreator } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
interface CountState {
count: number;
increasePopulation: () => void;
removeAll: () => void;
}
const useCountStore : StateCreator<CountState> = (set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
removeAll: () => set({ count: 0 }),
});
const persistedUseCountStore = persist<CountState>(
useCountStore,
{
name: 'countStore',
storage: createJSONStorage(() => sessionStorage), // session 사용
},
);
export default create(persistedUseCountStore);
👉 zustand
👉 zustand 깃헙