소개

Zustand는 React의 상태 관리를 간단하고 효율적으로 할 수 있게 도와주는 경량 상태 관리 라이브러리입니다.

Redux보다 보일러플레이트 코드가 적고, 사용법이 직관적이며 Hooks 기반으로 동작합니다.

 

특징

1. 간단한 사용법: React Hooks 스타일로 상태를 관리합니다.

2. 가벼운 라이브러리: 약 1KB로 매우 가볍습니다.

3. 보일러플레이트 최소화: 리듀서, 액션 정의 등이 필요 없습니다.

4. 직관적: 상태 정의 및 사용이 단순하고 명확합니다.

5. React에 최적화: React에서 사용하기 편리합니다.

 

설치
npm install zustand

 

 

기본 사용법
1. 상태 스토어 생성

Zustand는 create 함수를 사용해 상태 스토어를 정의합니다.

예시: store/CounterStore.ts

import { create } from "zustand";

// Zustand 스토어 생성
interface CounterState {
  count: number;
  increase: () => void;
  decrease: () => void;
}

export const useCounterStore = create<CounterState>((set) => ({
  count: 0, // 초기 상태
  increase: () => set((state) => ({ count: state.count + 1 })), // 상태 업데이트
  decrease: () => set((state) => ({ count: state.count - 1 })),
}));

 

2. 스토어 내보내기

예시: store/index.ts

export { useCounterStore } from "./counterStore";

// 아래와 같이 여러개의 스토어를 index.ts에서 한 번에 내보낼 수 있다
// export { useCartStore } from "./cartStore";
// export { useProductStore } from "./productStore";

 

3. 스토어 사용하기

컴포넌트에서 useCounterStore를 가져와 상태를 사용할 수 있습니다.

예시: components/Counter.tsx

import { useCounterStore } from "@/store";

const Counter = () => {
  const { count, increase, decrease } = useCounterStore();

  return (
    <div>
      <h1>카운터: {count}</h1>
      <button onClick={increase}>증가</button>
      <button onClick={decrease}>감소</button>
    </div>
  );
};

export default Counter;

 

주요 개념
1. 상태 읽기와 업데이트

state 읽기: useStore((state) => state.someProperty)를 사용해 특정 상태를 읽습니다.

set 함수: 상태를 업데이트하는 데 사용합니다.

 

2. 상태 분리와 재사용

Zustand를 사용하면 여러 스토어를 만들어 서로 독립적으로 관리할 수 있습니다.

예시: Auth 스토어

import { create } from "zustand";

interface AuthState {
  isLoggedIn: boolean;
  login: () => void;
  logout: () => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  isLoggedIn: false,
  login: () => set({ isLoggedIn: true }),
  logout: () => set({ isLoggedIn: false }),
}));

 

사용 예시

import { useAuthStore } from "@/store/useAuthStore";

const AuthComponent = () => {
  const { isLoggedIn, login, logout } = useAuthStore();

  return (
    <div>
      {isLoggedIn ? (
        <button onClick={logout}>로그아웃</button>
      ) : (
        <button onClick={login}>로그인</button>
      )}
    </div>
  );
};

 

중급 기능
1. Zustand에서 비동기 작업 처리

상태 업데이트를 비동기 함수로 처리할 수 있습니다.

import { create } from "zustand";

interface ProductState {
  products: string[];
  fetchProducts: () => Promise<void>;
}

export const useProductStore = create<ProductState>((set) => ({
  products: [],
  fetchProducts: async () => {
    const response = await fetch("/api/products");
    const data = await response.json();
    set({ products: data });
  },
}));

 

2. 상태 구독

Zustand는 불필요한 리렌더링을 방지하기 위해 부분 상태 구독이 가능합니다.

const count = useCounterStore((state) => state.count); // count만 구독
const increase = useCounterStore((state) => state.increase);