본문 바로가기

React

Zustand로 상태 관리하기

반응형

리액트 애플리케이션을 만들다 보면 컴포넌트 간에 상태를 공유하거나, 전역 상태 관리를 해야 할 때가 많습니다. Redux처럼 복잡한 상태 관리 라이브러리도 있지만, 설정이 번거롭고 코드가 길어질 수 있죠. 이런 점에서 Zustand는 매우 간단하고 직관적인 상태 관리 솔루션으로 주목받고 있습니다.

 

Zustand 상태 관리란?

 

Zustand(독일어로 "상태"라는 뜻)는 React 상태 관리 라이브러리입니다.
Redux보다 간단하고, Recoil보다 유연하고 직관적한 게 특징입니다.

 

npm install zustand

 

기본 사용법 

// store/counterStore.js
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;

 

// App.jsx
import useCounterStore from './store/counterStore';

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

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

 

 

Zustand 상태 분리 및 사용 예시

const useUserStore = create((set) => ({
  user: null,
  setUser: (user) => set({ user }),
}));

function UserProfile() {
  const { user, setUser } = useUserStore();

  return (
    <div>
      <h3>사용자 이름: {user?.name || '로그인 필요'}</h3>
      <button onClick={() => setUser({ name: '홍길동' })}>로그인</button>
    </div>
  );
}

 

비동기 상태 관리

const useAsyncStore = create((set) => ({
  data: null,
  loading: false,
  fetchData: async () => {
    set({ loading: true });
    const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const json = await res.json();
    set({ data: json, loading: false });
  },
}));

function FetchComponent() {
  const { data, loading, fetchData } = useAsyncStore();

  return (
    <div>
      <button onClick={fetchData}>데이터 불러오기</button>
      {loading && <p>로딩중...</p>}
      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
  );
}
반응형