Zustand란?

리액트 Context의 re-rendering 문제를 해결하기 위해 만들어진 상태 관리 라이브러리

특징

  1. 설치
yarn add zustand
  1. 프로젝트의 루트 디렉토리에 store 폴더를 생성
my-next-ts-app/
├── node_modules/
├── app/
│   ├── page.tsx
├── public/
├── styles/
├── store/
│   ├── useStore.ts
├── .gitignore
├── package.json
├── README.md
└── tsconfig.json
  1. store 만들기
// 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;
  1. 컴포넌트와 연결하기
// 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>
  );
}

Redux와 비교한 Zustand

전역 상태 라이브러리 비교하기


참고)