전역 상태관리 라이브러리 너무 어렵지 않나요? Recoil, Redux 넘 복잡해요…
최근에 정착한 간단하고 가벼운 상태관리인Zustand에 대해 정리해봤습니다!
Zustand는 독일어로 "상태(state)" 라는 뜻입니다.
React 앱에서 전역 상태를 간단하게 관리할 수 있도록 만든 가벼운 상태관리 라이브러리예요.
터미널에서 아래 명령어로 설치할 수 있습니다.
npm install zustand
# 또는
yarn add zustand
간단한 카운터 스토어를 만들어보겠습니다.
// counterStore.ts
import { create } from 'zustand'
interface CounterState {
count: number
increase: () => void
decrease: () => void
}
export const useCounterStore = create<CounterState>((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
decrease: () => set((state) => ({ count: state.count - 1 })),
}))
// CounterComponent.tsx
import React from 'react'
import { useCounterStore } from './counterStore'
function CounterComponent() {
const { count, increase, decrease } = useCounterStore()
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increase}>+1</button>
<button onClick={decrease}>-1</button>
</div>
)
}
| 특징 | 설명 |
|---|---|
| 가벼움 | Redux에 비해 훨씬 작은 번들 크기 |
| 단순한 API | create() 하나로 상태와 액션을 모두 정의 |
| React Context 미사용 | 별도 Provider 필요 없음 |
| 구독 기반 | 상태가 변경될 때 해당 컴포넌트만 리렌더링 |
| 미들웨어 확장 가능 | persist, devtools 등 미들웨어 추가 가능 |
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
export const useUserStore = create(
persist(
(set) => ({
username: '',
setUsername: (name: string) => set({ username: name }),
}),
{
name: 'user-storage', // localStorage 키
}
)
)
Zustand는 러닝커브가 거의 없고, 즉시 사용 가능한 간편한 상태관리 도구라고 합니다!
프로젝트가 커질수록 복잡도가 증가하면서 상태관리를 어떻게 해야할지 고민이 많았는데, 선택기준을 명확히해서 앞으로는 zustand를 도입해보려고 합니다 ..! 화이팅
읽어주셔서 감사합니다 :D