Zustand 轻量状态库
约 442 字大约 1 分钟
布欧-Lewyon
2026-05-15
Zustand 是一个极简的状态管理库,API 轻量、不依赖 Context、默认不需要 Provider。
安装
npm install zustandStore 定义
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface CartStore {
items: CartItem[]
addItem: (item: CartItem) => void
removeItem: (id: number) => void
clearCart: () => void
total: () => number
}
const useCartStore = create<CartStore>()(
persist( // 持久化到 localStorage
(set, get) => ({
items: [],
addItem: (item) => set((state) => ({
items: [...state.items, item]
})),
removeItem: (id) => set((state) => ({
items: state.items.filter(i => i.id !== id)
})),
clearCart: () => set({ items: [] }),
total: () => get().items.reduce((sum, i) => sum + i.price, 0),
}),
{ name: 'cart-storage' } // localStorage key
)
)组件中使用
function Cart() {
// 选择器:只订阅 items,变化时重渲染
const items = useCartStore(state => state.items)
const total = useCartStore(state => state.total())
const addItem = useCartStore(state => state.addItem)
const clearCart = useCartStore(state => state.clearCart)
return (
<div>
<button onClick={() => addItem({ id: Date.now(), name: '商品', price: 99 })}>
添加商品
</button>
<ul>
{items.map(i => <li key={i.id}>{i.name} - ¥{i.price}</li>)}
</ul>
<p>总计: ¥{total}</p>
<button onClick={clearCart}>清空</button>
</div>
)
}异步操作
interface UserStore {
user: User | null
loading: boolean
fetchUser: (id: number) => Promise<void>
}
const useUserStore = create<UserStore>((set) => ({
user: null,
loading: false,
fetchUser: async (id) => {
set({ loading: true })
try {
const res = await fetch(`/api/users/${id}`)
const user = await res.json()
set({ user, loading: false })
} catch {
set({ loading: false })
}
}
}))选择器优化
// ❌ 每次重渲染都返回新对象
const state = useCartStore() // 整个 store
// ✅ 选择器精确订阅
const items = useCartStore(state => state.items) // 仅 items
const total = useCartStore(state => state.total()) // 仅 total
// ✅ shallow 比较
import { shallow } from 'zustand/shallow'
const { items, addItem } = useCartStore(
state => ({ items: state.items, addItem: state.addItem }),
shallow
)Zustand vs Redux
| 对比 | Zustand | Redux Toolkit |
|---|---|---|
| 代码量 | 少 | 中 |
| 学习曲线 | 低 | 中 |
| TypeScript | 优秀 | 优秀 |
| 中间件 | 内置 persist/immer | Redux DevTools |
| 适用规模 | 中小型 | 大型 |
小结
- Zustand:
create()定义 store,返回 Hook。 - 选择器精确订阅,避免不必要重渲染。
persist中间件自动存入 localStorage。- 支持异步操作(async/await)。
- 无需 Provider 包裹,API 极简。
