Development/State

zustand가 뭐야 어떻게 써

yunicornlab 2024. 12. 11. 17:36
반응형

1. Zustand란?

크기가 작아서 가볍고 빠르며 확장성이 좋은 전역 상태 관리 라이브러리다. 

Zustand는 독일어로 "상태"라는 뜻이다. (독일어다보니 발음은 쭈스탄트 정도로 읽으면 된다.)

zustand는 store를 기반으로 하기 때문에 처음에 store에 대한 개념을 알아야 하는데, store는 간단히 말해 애플리케이션의 상태를 저장하는 중앙 데이터 저장소라고 생각하면 된다.

zustand는 create라는 함수를 통해 이 store를 생성하기 때문에, create 함수로 store를 생성하는 것부터가 시작이다.

2. Zustand 공식 홈페이지

(1) 공식 문서

https://zustand-demo.pmnd.rs/

 

Zustand

 

zustand-demo.pmnd.rs

 

보통은 해당 서비스의 소개 문구가 있는데, zustand는 대놓고 코드만 있다.

그만큼 사용하기 편하다는 것을 강조하는 듯 하다.

 

(2) Github

https://github.com/pmndrs/zustand

 

GitHub - pmndrs/zustand: 🐻 Bear necessities for state management in React

🐻 Bear necessities for state management in React. Contribute to pmndrs/zustand development by creating an account on GitHub.

github.com

깃허브에 가보면 Zustand는 Poimandres라는 오픈소스 팀에서 개발한 라이브러리인 걸 알 수 있다.

줄여서 pmnd라고 나오는데, 찾아보니까 Jotai와 React Spring도 이 팀에서 개발한 걸 알 수 있었다.
https://docs.pmnd.rs/

 

Poimandres documentation

Index of documentation for pmndrs/* libraries

docs.pmnd.rs

 

3. Zustand 설치

npm install zustand

(줄여서 npm i zustand도 가능)

yarn add zustand

 

 

4. Zustand를 사용해보자! Create 함수를 사용해 Store 생성하기 (JavaScript 기준)

상태와 액션이 저장될 Store를 생성하려면 zustand에서 제공하는 create 함수를 사용하면 된다.

create 함수는 일반적으로 콜백 함수 하나만 인자로 받는다. (더 확장하고 싶으면 persist나 immer와 같은 미들웨어를 추가할 수 있다.)

create 함수는 반환된 객체를 기반으로 상태와 상태 변경 함수를 정의한다.

이를 담는 변수는 use이름store로 지으면 된다.

그리고 객체를 반환해야하기 때문에 소괄호로 감싸줘야 한다.

(콜백을 화살표 함수로 작성할 것이기 때문에 명시적으로 중괄호 + return을 적어주거나 return 생략 + 소괄호 필요)

import { create } from 'zustand';

const useCountStore = create(() => ({}));

/*
const useCountStore = create(() => {
  return {};
});
*/

 

인자로 받는 콜백 함수는 set과 get을 받을 수 있다.

set은 상태를 업데이트하는 함수이고, get은 현재 상태를 가져올 수 있는 함수다. 

import { create } from 'zustand';

const useCountStore = create((set, get) => ({
  count: 0, // 초기 상태
  increase: () => set((state) => ({ count: state.count + 1 })), // 증가 함수
  decrease: () => set((state) => ({ count: state.count - 1 })), // 감소 함수
  reset: () => set({ count: 0 }), // 초기화 함수
  double: () => set({ count: get().count * 2 }), // 현재 상태를 읽어 2배로 설정
}));

 

 

 

이렇게 store를 생성하는 함수는 보통은 stores라는 폴더에 use이름Store.js라는 파일로 따로 둔다.

(자바스크립트면 .js, 타입스크립트면 .ts) (위의 예시로는 useCountStore.js)

스토어임을 명확히 표현하고 싶을 때는 접미사 store를 포함해서 "useCountStore.store.js" (useCountStore.store.ts)라고 쓰기도 한다.

 

이렇게 생성한 스토어의 상태와 액션을 사용하고 싶으면 사용할 컴포넌트에서 아래와 같이 가져오면 된다.

import useCountStore from './useCountStore';

const { count, increase, decrease, reset, double } = useCountStore();

 

 

하나만 가져오고 싶으면 아래처럼 필요한 값만 반환하는 형식을 사용할 수 있다.

const count = useCountStore((state) => state.count);

 

컴포넌트 사용 예시는 아래와 같다.

import useCountStore from './useCountStore';

const Counter = () => {
  // 상태와 액션 가져오기
  const { count, increase, decrease, reset, double } = useCountStore(); 

  return (
    <>
      <h1>Count: {count}</h1>
      <div>
        <button onClick={increase}>Increase</button>
        <button onClick={decrease}>Decrease</button>
        <button onClick={reset}>Reset</button>
        <button onClick={double}>Double</button> {/* count를 두 배로 */}
      </div>
    </>
  );
};

export default Counter;
반응형