Zustand State Management
Lightweight global state for React: stores, slices, middleware, persistence.
reactstatefrontend
# Zustand
## Install
```bash
npm install zustand
```
## Basic store
```ts
import { create } from 'zustand'
interface CountStore {
count: number
inc: () => void
dec: () => void
reset: () => void
}
export const useCountStore = create<CountStore>((set) => ({
count: 0,
inc: () => set((s) => ({ count: s.count + 1 })),
dec: () => set((s) => ({ count: s.count - 1 })),
reset: () => set({ count: 0 }),
}))
// Usage
const { count, inc } = useCountStore()
// Select to avoid re-renders:
const count = useCountStore((s) => s.count)
```
## Async actions
```ts
const useUserStore = create<UserStore>((set) => ({
users: [],
loading: false,
fetchUsers: async () => {
set({ loading: true })
const data = await fetch('/api/users').then(r => r.json())
set({ users: data, loading: false })
},
}))
```
## Slices pattern (large stores)
```ts
const createAuthSlice = (set) => ({
user: null,
login: (u) => set({ user: u }),
logout: () => set({ user: null }),
})
const createCartSlice = (set) => ({
items: [],
addItem: (item) => set((s) => ({ items: [...s.items, item] })),
})
export const useStore = create((...a) => ({
...createAuthSlice(...a),
...createCartSlice(...a),
}))
```
## Persist middleware
```ts
import { persist } from 'zustand/middleware'
const useStore = create(persist(
(set) => ({ theme: 'light', setTheme: (t) => set({ theme: t }) }),
{ name: 'app-storage', storage: createJSONStorage(() => localStorage) }
))
```
## Immer middleware (mutable updates)
```ts
import { immer } from 'zustand/middleware/immer'
const useStore = create(immer((set) => ({
todos: [],
toggle: (id) => set((s) => {
const todo = s.todos.find(t => t.id === id)
if (todo) todo.done = !todo.done // mutate safely
}),
})))
```
## Devtools
```ts
import { devtools } from 'zustand/middleware'
const useStore = create(devtools((set) => ({ ... }), { name: 'MyStore' }))
```API: /api/skills/zustand-state