为什么选Zustand?
- 比Redux简单,比Context高效
- 无Provider包裹需求
- 自动渲染优化
- 支持TS类型
基础用法
npm install zustand
创建store:
// counterStore.ts
import { create } from 'zustand'
export const useCounterStore = create((set) => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
reset: () => set({ count: 0 })
}))
组件中使用:
function Counter() {
const { count, increment } = useCounterStore()
return (
<div>
<span>{count}</span>
<button onClick={increment}>+1</button>
</div>
)
}
高级技巧
- 选择性订阅(优化性能):
const count = useCounterStore(state => state.count)
- 异步操作:
// store中
fetchData: async () => {
set({ loading: true })
const data = await api.getData()
set({ data, loading: false })
}
- 持久化:
import { persist } from 'zustand/middleware'
create(persist(() => ({...}), {
name: 'storage-key'
}))
Zustand以极简API提供了完整的状态管理方案,特别适合中小型React应用。