Overview
Zustand is a minimal state management library with a small API surface. It leverages React hooks for state management without boilerplate or middleware setup.
Key Features
- Minimal API: Store creation with a single function
- No Providers: Direct hook usage in components
- TypeScript Support: Full type inference
- Immer Integration: Immutable updates with Immer
- Devtools: Browser devtools integration for debugging
Quick Start
npm install zustand
Create Store
import { create } from 'zustand'
interface CounterStore {
count: number
increment: () => void
decrement: () => void
}
export const useCounterStore = create<CounterStore>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 }))
}))
Use in Components
export function Counter() {
const count = useCounterStore((state) => state.count)
const increment = useCounterStore((state) => state.increment)
return (
<button onClick={increment}>
Count: {count}
</button>
)
}
With Immer
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
export const useStore = create<State>()(
immer((set) => ({
todos: [],
addTodo: (todo) => set((state) => {
state.todos.push(todo)
})
}))
)
Zustand bundles to just 2.2kb gzipped, making it ideal for performance-critical applications.