Post

Zustand 상태 관리 라이브러리 활용법

Zustand 상태 관리 라이브러리 활용법

Zustand는 가볍고 사용하기 쉬운 상태 관리 라이브러리이다. Redux와 같은 다른 상태 관리 라이브러리보다 보일러플레이트 코드가 적고, 직관적인 API를 제공하기 때문에 러닝커브가 낮아 빠르게 적용할 수 있다. 특히 React 애플리케이션에서 전역 상태를 효율적으로 관리할 수 있으며, 상태 변경이 필요한 컴포넌트만 리렌더링되도록 최적화되어 있다.


1. Zustand를 선택한 이유

💡 Zustand를 선택한 주요 이유

보일러플레이트 코드가 적다 → Redux처럼 action, reducer, dispatch가 필요 없음

사용법이 직관적create() 함수로 간단하게 스토어 생성 가능

불필요한 리렌더링 방지 → 상태를 구독한 컴포넌트만 리렌더링됨

작은 번들 크기zustand 패키지는 약 1KB 정도로 가볍다

TypeScript 지원이 우수함타입 추론이 자연스럽게 동작하여 개발 생산성 향상


2. Zustand 설치하기

Zustand는 NPM 또는 Yarn을 사용하여 설치할 수 있다.

1
2
3
4
npm install zustand
# 또는
yarn add zustand


3. Zustand 기본 사용법

✅ 3-1. 간단한 스토어 만들기

Zustand에서는 create() 함수를 사용하여 스토어를 쉽게 만들 수 있다.

1
2
3
4
5
6
7
8
9
10
import { create } from "zustand";

// 상태(스토어) 생성
const useCounterStore = create((set) => ({
  count: 0,
  increase: () => set((state) => ({ count: state.count + 1 })),
  decrease: () => set((state) => ({ count: state.count - 1 }))
}));

export default useCounterStore;

create() 함수를 사용하여 Zustand 스토어를 생성한다.

set() 함수를 통해 상태를 업데이트할 수 있다.


✅ 3-2. Zustand 스토어 사용하기

Zustand의 상태를 컴포넌트에서 쉽게 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import useCounterStore from "../store/counterStore";

const Counter = () => {
  // Zustand 스토어에서 상태와 액션 가져오기
  const { count, increase, decrease } = useCounterStore();

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

export default Counter;

useCounterStore()를 호출하면 count, increase, decrease 상태를 가져올 수 있다.

increase()decrease() 함수를 호출하면 상태가 변경되며, 해당 컴포넌트만 리렌더링된다.


4. Zustand의 고급 기능

Zustand는 단순한 상태 관리뿐만 아니라 비동기 상태 관리, 미들웨어 적용, 타입스크립트 지원 등의 다양한 기능을 제공한다.


✅ 4-1. 비동기 상태 관리 (API 호출)

Zustand에서 set()을 활용하여 비동기 API 호출도 쉽게 관리할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { create } from "zustand";

// 비동기 상태 관리
const useUserStore = create((set) => ({
  user: null,
  fetchUser: async () => {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users/1"
    );
    const data = await response.json();
    set({ user: data });
  }
}));

export default useUserStore;

사용 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import useUserStore from "../store/userStore";

const UserProfile = () => {
  const { user, fetchUser } = useUserStore();

  return (
    <div>
      <h1>User Profile</h1>
      <button onClick={fetchUser}>사용자 정보 가져오기</button>
      {user && <p>{user.name}</p>}
    </div>
  );
};

export default UserProfile;

fetchUser() 함수가 호출되면 API 요청을 보낸 후 상태가 업데이트된다.

✔ API 응답이 도착하면 user 상태가 변경되며, 자동으로 UI가 업데이트된다.


✅ 4-2. Zustand와 TypeScript

Zustand는 TypeScript와 완벽하게 호환되며, 아래와 같이 타입을 지정할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { create } from "zustand";

interface CounterState {
  count: number;
  increase: () => void;
  decrease: () => void;
}

const useCounterStore = create<CounterState>((set) => ({
  count: 0,
  increase: () => set((state) => ({ count: state.count + 1 })),
  decrease: () => set((state) => ({ count: state.count - 1 }))
}));

export default useCounterStore;

✔ Zustand의 상태와 액션을 인터페이스로 정의하여 타입 안정성을 높일 수 있다.


✅ 4-3. 미들웨어 적용 (로깅, persist 저장 등)

Zustand는 미들웨어를 적용하여 상태 변경 로그 기록, 로컬 스토리지 저장 등을 쉽게 구현할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";

// persist: 상태를 로컬 스토리지에 저장
const useUserStore = create(
  persist(
    (set) => ({
      name: "Guest",
      setName: (name) => set({ name })
    }),
    {
      name: "user-storage" // 로컬 스토리지 키 이름
    }
  )
);

export default useUserStore;

persist() 미들웨어를 사용하면 상태가 로컬 스토리지에 자동으로 저장된다.

✔ 페이지를 새로고침해도 기존 상태가 유지된다.


5. Zustand와 Redux 비교

비교 항목ZustandRedux
설치 크기1KB 미만 (가벼움)6KB 이상
보일러플레이트 코드적음 (간단한 API)많음 (actions, reducers 필요)
상태 업데이트set() 함수 사용dispatch + reducer 필요
성능 최적화자동으로 구독한 상태만 업데이트직접 최적화 필요
비동기 처리직접 가능redux-thunk, redux-saga 필요
미들웨어devtools, persist 지원다양한 미들웨어 존재

✔ Zustand는 Redux보다 코드가 간결하고, 사용하기 쉬우며, 성능 최적화가 자동으로 이루어진다.

✔ 하지만 대규모 프로젝트에서는 Redux가 더 적합할 수 있다.


6. Zustand를 실제 프로젝트에서 활용한 경험

🔹 Zustand를 사용한 프로젝트 사례

대시보드 프로젝트에서 전역 상태 관리를 위해 Zustand를 활용

✅ Redux보다 가벼운 상태 관리가 필요할 때 사용

비동기 API 관리(useQuery와 함께 사용)

✅ Zustand의 persist 기능을 활용하여 사용자 로그인 상태 유지

실제로 Zustand를 적용해 본 결과, Redux에 비해 코드가 훨씬 간결하고 불필요한 리렌더링을 방지할 수 있었다.

특히, 로컬 스토리지와의 연동(persist), TypeScript 지원, 미들웨어 활용 등이 매우 편리했다.


🎯 결론

✔ Zustand는 가볍고, 사용이 간편한 React 상태 관리 라이브러리이다.

보일러플레이트 코드가 적고, 성능 최적화가 자동으로 이루어지며, TypeScript 지원이 우수하다.

✔ Redux보다 간단한 상태 관리가 필요한 프로젝트에 적합하며, 비동기 API 관리, 전역 상태 공유, 로컬 스토리지 저장 등에 효과적이다.

🚀 Zustand를 사용하면 더 빠르고 효율적인 상태 관리가 가능하다!

This post is licensed under CC BY 4.0 by the author.