React Zustand

정현승·2024년 12월 4일

Zustand

Zustand는 가볍고 직관적인 상태 관리 라이브러리로, 간단한 API와 뛰어난 성능을 제공합니다.
Redux나 MobX와 같은 상태 관리 라이브러리보다 간결하게 상태를 정의하고 사용할 수 있습니다.

npm install zustand

Zustand 기본 사용법

1. 상태 스토어 생성

Zustand의 create 함수를 사용해 상태와 업데이트 함수를 정의합니다.

import { create } from "zustand";

interface CounterState {
  count: number;
  increment: () => void;
  decrement: () => void;
}

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

2. 상태 사용

컴포넌트에서 useCounterStore를 호출하여 상태를 가져옵니다.

import { useCounterStore } from "./store/counterStore";

export default function Counter() {
  const { count, increment, decrement } = useCounterStore();

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

3. 상태 셀렉터 사용

Zustand는 특정 상태만 선택해서 사용할 수 있는 셀렉터 기능을 제공합니다. 이는 불필요한 상태 업데이트를 방지합니다.

import { useCounterStore } from "./store/counterStore";

export default function CounterDisplay() {
  const count = useCounterStore((state) => state.count); // 특정 상태만 선택

  return <h1>Count: {count}</h1>;
}

4. 비동기 데이터 로딩

import { create } from "zustand";

interface UserState {
  user: { name: string; age: number } | null;
  fetchUser: () => Promise<void>;
}

export const useUserStore = create<UserState>((set) => ({
  user: null,
  fetchUser: async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
    const data = await response.json();
    set({ user: data });
  },
}));
import React, { useEffect } from "react";
import { useUserStore } from "./store/userStore";

export default function UserProfile() {
  const { user, fetchUser } = useUserStore();

  useEffect(() => {
    fetchUser();
  }, []);

  return (
    <div>
      {user ? <h1>{user.name}</h1> : <p>Loading user...</p>}
    </div>
  );
}
  • 간결한 코드: 상태와 업데이트 함수를 간단히 정의.
  • 리렌더 최소화: 셀렉터를 통해 상태 변경에 의한 리렌더링을 최소화.
  • 비동기 작업 간편: 비동기 상태 관리도 쉽게 구현.

0개의 댓글