sohyeon kim

[React] Zustand : 너무나 가벼운 상태관리 라이브러리 본문

React

[React] Zustand : 너무나 가벼운 상태관리 라이브러리

aotoyae 2024. 8. 7. 17:02
728x90

 

 

💡 작고(small) 빠르고(fast) 확장가능한(scalable) 상태관리 솔루션

 

 

yarn add zustand & 스토어 생성

 

bearsStore.js

import { create } from 'zustand';

const useBearsStore = create((set) => {
  return {
    bears: 0, // 초기값
    increase: () => { // 1씩 증가
      set((state) => ({ bears: state.bears + 1 }));
    },
    init: () => set({ bears: 0 }), // 초기화
  };
});

export default useBearsStore;

 

App.jsx

function App() {
  // const bears = useBearsStore(function (state) {
  //   return state.bears;
  // });

  // const increase = useBearsStore(function (state) {
  //   return state.increase;
  // });

  const { bears, increase, init } = useBearsStore((state) => state); // 구조분해

  return (
    <div>
      <h1>zustand</h1>
      <h4>{bears}</h4>
      <button onClick={increase}>+1</button>
      <button onClick={init}>init</button>
    </div>
  );
}

 

Redux 에 비해 보일러 플레이트가 훨씬 적고 상태 정의 과정이 직관적이다.

 

💡Zustand VS Redux Toolkit

  장점 단점
Zustand 간단하고 빠르며, 설정이 매우 쉬움 상태가 커지면 관리가 어려울 수 있음
Redux Toolkit 구조화된 방법을 통해 대규모 애플리케이션에서도 관리가 용이 설정이 복잡하고, 학습 곡선이 가파름

 

 

 

728x90
반응형