pnpm으로 Zustand 설치 및 빠른 시작 가이드
Zustand는 Redux보다 가볍고 Context API보다 사용법이 간단한 상태 관리 라이브러리예요. pnpm으로 프로젝트에 Zustand를 적용하는 단계를 정리했어요.
1. pnpm으로 패키지 설치
터미널에서 프로젝트 루트 경로로 이동한 뒤 아래 명령어로 설치해요.
Bash
pnpm add zustand
2. Store 생성하기
Zustand는 create 함수로 스토어를 정의해요. 별도의 Provider 설정 없이 바로 쓸 수 있어요.
TYPESCRIPT
import { create } from 'zustand'
// 상태(State)와 액션(Action)의 타입 정의
interface CounterState {
count: number
increment: () => void
decrement: () => void
}
// 스토어 생성 후 내보내기
export const useCounterStore = create<CounterState>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}))
3. 컴포넌트에서 사용하기
컴포넌트 안에서 스토어를 Hook처럼 호출해요. selector로 필요한 값만 골라 쓰면, 그 값이 바뀔 때만 컴포넌트가 다시 렌더링돼요. 인자 없이 useCounterStore()를 부르면 스토어 전체를 구독해서 어떤 값이 바뀌어도 다시 렌더링돼요.
React + TS
import { useCounterStore } from './store'
function CounterComponent() {
// 필요한 상태와 함수를 하나씩 선택
const count = useCounterStore((state) => state.count)
const increment = useCounterStore((state) => state.increment)
const decrement = useCounterStore((state) => state.decrement)
return (
<div>
<h1>값: {count}</h1>
<button onClick={increment}>증가</button>
<button onClick={decrement}>감소</button>
</div>
)
}
4. 핵심 요약
- Zero Config: 별도의 Context Provider나 환경 설정이 필요 없어요.
- Simple API:
set함수로 상태를 바꾸고, 컴포넌트에서는 Hook으로 불러와요. - Selector: 필요한 값만 골라 구독하면 불필요한 렌더링을 줄일 수 있어요.