[Frontend] Zustand에 대해서

2025. 4. 14. 17:26·Frontend

Zustand는 프레임워크 독립적인 상태관리 라이브러리중 하나입니다.

 

Store라는 개념을 이용하여 불필요한 props전달을 최소화합니다.

 

다음과 같이 설치합니다.

npm install zustand

 

※ Zustand는 현재 프레임워크 독립 라이브러리이나, 처음에는 React 전용 라이브러리로 개발되었습니다. 따라서 아래는 React를 기준으로 서술하였습니다.

create( )

Store를 생성하는 함수입니다.

 

속성값과 메소드를 포함한 객체를 반환하며, Store 안에서 속성값은 State, 메소드는 Action이라고 표현합니다.

 

기본적으로 set과 get 두 가지 매개변수를 받습니다.

 

get 함수는 자기 자신 Store 객체를 반환합니다.

 

set 함수는 Store의 값을 설정할 수 있습니다. 만약 인수로 콜백함수를 사용한다면, get( ) 사용 없이 바로 자기 자신 객체를 사용할 수 있습니다.

 

이름의 경우, 관습적으로 use~Store의 형식으로 짓는다고 합니다.

import { create } from 'zustand'

export const accountStore = create((set, get) => {
  return {
    name: "Jhon",  // state
    age: 18,  // state
    
    initAge: set({age: 20}),  // action
    
    decreaseAge: () => {  // action
      const { age } = get();
      set({ age: age - 1 })
    }
    
    increaseAge: set((state) => ({ age: state.age + 1 })),  // action
  }
})

사용하기

다음과 같이 사용하고자 하는 state 혹은 action을 호출하는 형태의 콜백과 함께 사용합니다.

 

이 경우 콜백으로 호출한 값이 변경될 때만 컴포넌트가 다시 랜더링됩니다.

import { useStore } from './store/bear-store.js';

BearCounter = () => {
  const bears = useStore((state) => state.bears);
  return <h1>곰이 {bears}마리 있습니다.</h1>
}

Controls = () => {
  const increasePopulation = useStore((state) => state.increasePopulation);
  return <button onClick={increasePopulation}>한마리 추가</button>
}

필요한 때에만 값을 불러오려면 아래와 같이 사용할 수도 있습니다.

 

단, 이 때는 해당 코드가 실행될 때의 상태값만 읽어보기 때문에 지속적으로 값의 변화는 추척하지 않습니다.

const increasePopulation = useStore.getState().increasePopulation;
  useStore(state => state.###) useStore.getState().###
React Hook O X
값 추적 O X
사용처 컴포넌트 안 어디든

 

Store에서 불러와야 하는 값들이 많다면, 아예 store 전체를 불러오는 것도 가능합니다.

const useSys = useStore(state => state);

하지만 이 경우, 모든 상태값에 대해 컴포넌트가 다시 랜더링되기 때문에 성능 저하가 발생할 수 있어 권장하지는 않습니다.

주의사항

Zustand의 set( ) 함수는 비동기 함수이기 때문에, 실행 후 바로 값이 반영되지 않습니다.

useMyStore.getState().setConfig(...)
console.log(useMyStore.getState().config) // 이전 상태가 출력됨

 

https://zustand.docs.pmnd.rs/getting-started/introduction

 

Introduction - Zustand

How to use Zustand

zustand.docs.pmnd.rs

 

※ TypeScript에서의 제네릭 사용은 다음과 같이 합니다.

import { create } from 'zustand'

export const accountStore = create<{
  name: string,
  age: number,
  initAge: () => void,
  decreaseAge: () => void,
  increaseAge: () => void,
}>((set, get) => {
  return {
    // ...
  }
})
728x90

'Frontend' 카테고리의 다른 글

[Three] 02. Scene  (0) 2025.05.10
[Three] 01. Three.js 기본 구성 요소 - Renderer, Scene, Camera  (0) 2025.05.04
[Fronted] 상태관리 라이브러리  (0) 2025.04.14
[Three] Three.js 프로젝트 시작하기  (0) 2025.01.12
[Three] Three.js에 대해서  (0) 2025.01.12
'Frontend' 카테고리의 다른 글
  • [Three] 02. Scene
  • [Three] 01. Three.js 기본 구성 요소 - Renderer, Scene, Camera
  • [Fronted] 상태관리 라이브러리
  • [Three] Three.js 프로젝트 시작하기
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (276)
      • CS (40)
        • CV (2)
        • PS (34)
      • Reveiw (18)
        • Paper (18)
        • Github (0)
      • ML (8)
        • Pytorch (5)
      • Language (59)
        • Python (8)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (77)
        • React (8)
        • ReactNative (6)
        • SolidJS (20)
        • CSS (12)
      • Backend (44)
        • DB (18)
        • Node.js (11)
      • UI (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    expo
    mongo
    ML
    CSS
    postgresql
    ReactNative
    backend
    react
    PRISMA
    js
    ts
    frontend
    python
    Three
    Express
    API
    Git
    CV
    modal
    ps
    nodejs
    figma
    SOLID
    review
    deploy
    CS
    GAN
    vscode
    DB
    PyTorch
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[Frontend] Zustand에 대해서
상단으로

티스토리툴바