
Zustand:Store 就是一个 Hook
1.2KB,无 provider,无样板代码。
import { create } from 'zustand'
export const useCartStore = create((set) => ({
items: [],
total: 0,
addItem: (product, qty) => set((state) => {
const existing = state.items.find(i => i.id === product.id)
const items = existing
? state.items.map(i => i.id === product.id ? { ...i, qty: i.qty + qty } : i)
: [...state.items, { ...product, qty }]
return { items, total: items.reduce((s, i) => s + i.price * i.qty, 0) }
}),
clearCart: () => set({ items: [], total: 0 }),
}))

细粒度选择器
const count = useCartStore(state => state.items.length) // 仅在 count 变化时重新渲染
const { clearCart } = useCartStore() // 稳定引用

Immer + 持久化
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { persist } from 'zustand/middleware'
const useStore = create(persist(immer((set) => ({
todos: [],
addTodo: (text) => set(state => { state.todos.push({ id: Date.now(), text, done: false }) }),
})), { name: 'app-state' }))

Slices 模式
const createAuth = (set) => ({
user: null,
login: async (creds) => { const user = await auth(creds); set({ user }) },
logout: () => set({ user: null }),
})
export const useStore = create((...args) => ({ ...createAuth(...args) }))
-> 使用 JSON Viewer 调试 store 状态。