리액트 Context의 re-rendering 문제를 해결하기 위해 만들어진 상태 관리 라이브러리
특징
yarn add zustand
my-next-ts-app/
├── node_modules/
├── app/
│ ├── page.tsx
├── public/
├── styles/
├── store/
│ ├── useStore.ts
├── .gitignore
├── package.json
├── README.md
└── tsconfig.json
// store/useStore.ts
import create from 'zustand';
type State = {
count: number;
increaseCount: () => void;
decreaseCount: () => void;
};
//create 함수는 상태와 액션을 정의하는 함수를 인자로 받아 zustand 스토어를 생성합니다.
const useStore = create<State>((set) => ({
count: 0,
increaseCount: () => set((state) => ({ count: state.count + 1 })),
decreaseCount: () => set((state) => ({ count: state.count - 1 })),
}));
export default useStore;
// app/page.tsx
"use client";
import useStore from '../store/useStore';
export default function Home() {
//useStore 훅을 사용하여 상태와 액션을 가져옵니다.
const count = useStore((state) => state.count);
const increaseCount = useStore((state) => state.increaseCount);
const decreaseCount = useStore((state) => state.decreaseCount);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increaseCount}>Increase</button>
<button onClick={decreaseCount}>Decrease</button>
</div>
);
}
참고)