Zustand 상태관리 라이브러리

Sunki-Kim·2024년 1월 16일
0

React

목록 보기
7/7

Zustand는 독일어로 '상태'를 의미한다. 작은 패키지 사이즈와 직관적인 코드 작성을 특징으로 가진다.(보일러플레이트 감소)

Zustand는 하나의 스토어를 중앙 집중형으로 활용해서 스토어 내부에서 상태를 관리한다.

최근 npm trend로 비교했을때 , 많은 개발자들이 직관적이고 사용하기 쉬운 상태관리로 채택하는 추세이다.

  • 특별히 많은 코드를 작성하지 않아도 빠르게 스토어 작성이 가능하다.
    -> 이는 Redux에 대비했을때, 코드량이 현저히 감소하며, 빠르게 상태를 정의하기 때문에, 한결 가볍다.
  • 미들웨어를 지원한다. (persist, immer, sessionStorage 저장)
  • Redux Devtools 사용가능

Store 생성 (typescript)

// store.tsx
import { create } from "zustand";
import { devtools } from "zustand/middleware";

type BearStore = {
  bears: number;
  increaseBear: () => void; // action type 지정
  removeAllBears: () => void;
};

export const useBearStore = create<BearStore>()(
  devtools((set) => ({ // devtools로 감싸서 debuging
    bears: 0,
    increaseBear: () => set((state) => ({ bears: state.bears + 1 })),
    removeAllBears: () => set({ bears: 0 }),
  }))
);

Component 구현

// ZustandComponent.tsx
import { useBearStore } from "../store/store"

const ZustandComponent = () => {
  	// STATE
  	const { bears, increaseBear, removeAllBears } = useBearStore();
  
	return (
    <>
      	<h2 className="text-4xl">{bears}</h2>
      	<button
       	 className="py-2 px-4 border bg-slate-100 rounded-md"
       	 onClick={() => increaseBear()}
      	>
       	 	Increase Bear
      	</button>
      	<button
        	className="py-2 px-4 border bg-slate-100 rounded-md"
        	onClick={() => removeAllBears()}
      	>
        	remove All Bear
      	</button>
    </>
  	);
};

export default ZustandComponent;

다음과 같이 만들어 진 store를 import하여 필요한 곳에서 사용이 가능하다.

다른 컴포넌트와 특별한 차이점은 Component 외부에서 Action을 취할 수 있고, state에 대한 액션 네이밍이 커스텀이 가능한 부분이다.(전역변수 호출)

소스코드

profile
당신에게 가치있는 Developer가 되고자

0개의 댓글