mcpField
Z
zustand

zustand

github.com/marcioaltoe开发060 次安装1 天前更新
代码仓库

关于 zustand

zustand 是面向 React 开发者的轻量状态管理技能,介绍 Store 创建、TypeScript 模式、中间件,以及 Next.js 等场景的实践方法。

主要功能

  1. 01无需 Provider 的 Hook 式 Store
  2. 02TypeScript Store 创建模式
  3. 03选择器与浅比较
  4. 04用于持久化和更新的中间件
  5. 05大型 Store 的切片组织

适用场景

  1. 01构建基础 React Store
  2. 02将状态持久化到 localStorage
  3. 03在 React 中使用原生 Store
  4. 04在 Next.js 中组织 Store

安装

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

$npx skills add https://github.com/marcioaltoe/skills --skill zustand

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

包含的文件

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

agents/
openai.yaml
references/
apis.md
middlewares.md
patterns.md
typescript.md

详细介绍

Zustand

适用于 React 的轻量级状态管理。无需 Provider,无需样板代码。Store 即 Hook。

快速开始

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 components — select only what you need
const bears = useBearStore((state) => state.bears)

关键规则

  1. TypeScript: 使用柯里化形式 create<T>()(...) — 这是类型推断所必需的
  2. 不可变性: 将状态视为不可变。set 只会进行一层浅合并
  3. 选择器: 始终选择特定字段,而不是整个 Store。对于返回新引用的多字段选择器,使用 useShallow
  4. 中间件顺序: devtools 必须放在最外层:devtools(persist(immer(...)))
  5. Next.js: 通过 createStore + Context 为每个请求创建 Store,切勿使用全局 create
  6. 嵌套更新: 深层嵌套使用 Immer,浅层嵌套使用展开运算符

如何选择

需求解决方案
基础 React Storecreate<T>()(...)
Vanilla(非 React)Store来自 zustand/vanilla 的 createStore
在 React 中使用 Vanilla StoreuseStore(store, selector)
自动推断类型(无需接口)combine 中间件
持久化到 localStoragepersist 中间件
Redux DevToolsdevtools 中间件
类可变方式更新immer 中间件
在外部订阅状态切片subscribeWithSelector 中间件
多字段且不触发重新渲染useShallow 包装器
大型 Store 模块化使用 StateCreator 的 Slices 模式
Next.js App RoutercreateStore + Context + Provider
重置 Storeset(initialState) 或 store.getInitialState()

参考资料

  • API 参考(create、createStore、hooks、shallow):参见 references/apis.md
  • TypeScript 模式(柯里化 create、slices、中间件类型、自定义中间件):参见 references/typescript.md
  • 中间件(persist、devtools、immer、redux、combine、subscribeWithSelector):参见 references/middlewares.md
  • 模式与最佳实践(Next.js、测试、重置、自动选择器、SSR、深层更新):参见 references/patterns.md

评论

支持 Markdown