Zustand state management for React and vanilla JavaScript. Use when creating stores, using selectors, persisting state to localStorage, integrating devtools, or managing global state without Redux complexity. Triggers on zustand, create(), createStore, useStore, persist, devtools, immer middleware.
极简状态管理——无需提供者,最少样板代码。
typescript
import { create } from zustand
interface BearState {
bears: number
increase: (by: number) => void
}
const useBearStore = create
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by })),
}))
// 在组件中——只选择你需要的内容
const bears = useBearStore((state) => state.bears)
const increase = useBearStore((state) => state.increase)
typescript
// 扁平更新(单层自动合并)
set({ bears: 5 })
set((state) => ({ bears: state.bears + 1 }))
// 嵌套对象(需要手动展开)
set((state) => ({
nested: { ...state.nested, count: state.nested.count + 1 }
}))
// 替换整个状态(不合并)
set({ bears: 0 }, true)
typescript
// 良好——仅订阅 bears
const bears = useBearStore((state) => state.bears)
// 糟糕——任何变化都会重新渲染
const state = useBearStore()
// 使用 useShallow 获取多个值(通过浅比较防止重新渲染)
import { useShallow } from zustand/react/shallow
const { bears, fish } = useBearStore(
useShallow((state) => ({ bears: state.bears, fish: state.fish }))
)
// 数组解构同样有效
const [bears, fish] = useBearStore(
useShallow((state) => [state.bears, state.fish])
)
typescript
// 获取当前状态(非响应式)
const state = useBearStore.getState()
// 更新状态
useBearStore.setState({ bears: 5 })
// 订阅状态变化
const unsub = useBearStore.subscribe((state) => console.log(state))
unsub() // 取消订阅
typescript
import { createStore } from zustand/vanilla
const store = createStore((set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by })),
}))
store.getState().bears
store.setState({ bears: 10 })
store.subscribe((state) => console.log(state))
| 模式 | 使用场景 |
|---|---|
| 单个选择器 | 需要单个状态片段 |
| useShallow |
该技能支持在以下平台通过对话安装:
帮我安装 SkillHub 和 zustand-state-1775975341 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 zustand-state-1775975341 技能
skillhub install zustand-state-1775975341
文件大小: 10.46 KB | 发布时间: 2026-4-13 12:43