Zustand란?
포스트
취소

Zustand란?

Zustand란

  • React 애플리케이션에서 전역 상태 관리를 간단하게 처리할 수 있도록 도와주는 경량 상태 관리 라이브러리
  • 독일어로 상태(State)를 의미한다.

특징

  • 경량 라이브러리
    • 라이브러리의 크기가 작고 가볍다.
    • 기본 번들 크기가 1KB 미만이다.
  • 보일러플레이트 없음
    • Redux처럼 복잡한 설정을 하지 않아도 된다.
    • action type, reducer, dispatch 등이 해당한다.
  • React 외부에서도 사용 가능
    • React 컴포넌트 밖에서도 상태를 읽거나 업데이트할 수 있다.
  • 미들웨어 지원
    • 다양한 미들웨어 기능을 내장하고 있다.
    • 로깅, persist 등이 해당한다.
  • Typescript 지원

라이브러리 받기

npm install zustand

기본 사용법

스토어 생성

// store.js
import { create } from 'zustand'

const useStore = create((set) => ({
  count: 0,
  increase: () => set((state) => ({ count: state.count + 1 })),
  decrease: () => set((state) => ({ count: state.count - 1 })),
}))

export default useStore

컴포넌트에서 사용

// Counter.jsx
import useStore from './store'

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

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increase}>+</button>
      <button onClick={decrease}>-</button>
    </div>
  )
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.