mcpField
Z
zustand-state

zustand-state

github.com/existential-birds开发85255 次安装11 周前更新
代码仓库

关于 zustand-state

zustand-state 是介绍 TypeScript 和 React 中 Zustand 状态管理的技能,涵盖存储更新、选择器、组件外访问、原生存储,以及 persist 和 devtools 中间件的审查要求。

主要功能

  1. 01创建并更新 Zustand 存储
  2. 02选择状态以减少重新渲染
  3. 03在组件外访问和订阅
  4. 04使用不依赖 React 的原生存储
  5. 05检查 persist 和 devtools 安全要求

适用场景

  1. 01管理 React 应用中的状态
  2. 02为组件选择所需状态
  3. 03将存储连接到外部系统
  4. 04审查持久化和 DevTools 配置

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/existential-birds/beagle --skill zustand-state

安装后在 Claude Code 中输入/zustand-state确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

MIDDLEWARE.md
PATTERNS.md
TYPESCRIPT.md
references/
middleware.md
patterns.md
typescript.md

详细介绍

Zustand 状态管理

简约的状态管理——无需 Provider,样板代码极少。

快速参考

import { create } from 'zustand'

interface BearState {
  bears: number
  increase: (by: number) => void
}

const useBearStore = create<BearState>()((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
}))

// In component - select only what you need
const bears = useBearStore((state) => state.bears)
const increase = useBearStore((state) => state.increase)

状态更新

// Flat updates (auto-merged at one level)
set({ bears: 5 })
set((state) => ({ bears: state.bears + 1 }))

// Nested objects (manual spread required)
set((state) => ({
  nested: { ...state.nested, count: state.nested.count + 1 }
}))

// Replace entire state (no merge)
set({ bears: 0 }, true)

选择器与性能

// Good - subscribes only to bears
const bears = useBearStore((state) => state.bears)

// Bad - rerenders on any change
const state = useBearStore()

// Multiple values with useShallow (prevents rerenders with shallow comparison)
import { useShallow } from 'zustand/react/shallow'

const { bears, fish } = useBearStore(
  useShallow((state) => ({ bears: state.bears, fish: state.fish }))
)

// Array destructuring also works
const [bears, fish] = useBearStore(
  useShallow((state) => [state.bears, state.fish])
)

在组件外访问

// Get current state (non-reactive)
const state = useBearStore.getState()

// Update state
useBearStore.setState({ bears: 5 })

// Subscribe to changes
const unsub = useBearStore.subscribe((state) => console.log(state))
unsub() // unsubscribe

Vanilla Store(无 React)

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获取多个值并避免重新渲染
getState()在 React 外部或事件处理程序中使用
subscribe()用于外部系统、日志记录
Vanilla store用于非 React 环境

门槛(persist 和 devtools)

合并使用这些中间件的代码前(设置方法请参阅 references/middleware.md):

  1. persist —— 通过条件: 持久化键是明确指定的(使用 partialize 或经过审核的完整状态快照),且写入存储的 JSON 不包含身份验证令牌、API 密钥或其他机密信息。
  2. 已发布构建中的 devtools —— 通过条件: DevTools 仅在开发环境中运行(通过环境变量控制),或者在 PR 中留下一行说明,解释为何在生产环境中保持启用。

评论

支持 Markdown