nextjs-zustand

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zustand for Next.js 16

在 Next.js 16 中使用 Zustand

Minimal, scalable state management with React 18+ useSyncExternalStore.
基于React 18+ useSyncExternalStore的轻量级、可扩展状态管理方案。

Agent Workflow (MANDATORY)

Agent 工作流(强制要求)

Before ANY implementation, use
TeamCreate
to spawn 3 agents:
  1. fuse-ai-pilot:explore-codebase - Analyze existing stores and state patterns
  2. fuse-ai-pilot:research-expert - Verify latest Zustand v5 docs via Context7/Exa
  3. mcp__context7__query-docs - Check middleware and TypeScript patterns
After implementation, run fuse-ai-pilot:sniper for validation.

在进行任何实现之前,使用
TeamCreate
生成3个Agent:
  1. fuse-ai-pilot:explore-codebase - 分析现有状态存储和状态模式
  2. fuse-ai-pilot:research-expert - 通过Context7/Exa验证最新的Zustand v5文档
  3. mcp__context7__query-docs - 检查中间件和TypeScript模式
实现完成后,运行fuse-ai-pilot:sniper进行验证。

Overview

概述

When to Use

使用场景

  • Managing client-side state in Next.js App Router applications
  • Need global state across Client Components only
  • Persisting state to localStorage/sessionStorage
  • Building UI state (modals, sidebars, theme, cart)
  • Replacing React Context for complex state
  • 在Next.js App Router应用中管理客户端状态
  • 仅需要在Client Components之间共享全局状态
  • 将状态持久化到localStorage/sessionStorage
  • 构建UI状态(模态框、侧边栏、主题、购物车)
  • 替代React Context处理复杂状态

Why Zustand v5

选择Zustand v5的原因

FeatureBenefit
Minimal APISimple create() function, no boilerplate
React 18 nativeuseSyncExternalStore, no shims needed
TypeScript firstFull inference with currying pattern
Middleware stackdevtools, persist, immer composable
Bundle size~2KB gzipped, smallest state library
No providersDirect store access, no Context wrapper

特性优势
极简API简单的create()函数,无需冗余代码
原生支持React 18基于useSyncExternalStore,无需垫片
优先支持TypeScript通过柯里化模式实现完整类型推断
中间件栈devtools、persist、immer可组合使用
包体积压缩后约2KB,体积最小的状态管理库之一
无需Provider直接访问状态存储,无需Context包装器

Critical Rules

核心规则

  1. Client Components ONLY - Never use Zustand in Server Components
  2. Context pattern for App Router - Avoid global stores (request isolation)
  3. useShallow for arrays/objects - Prevent unnecessary re-renders
  4. skipHydration with persist - Required for SSR compatibility
  5. Currying syntax v5 -
    create<State>()((set) => ({...}))
  6. SOLID paths - Stores in
    modules/[feature]/src/stores/

  1. 仅用于Client Components - 绝不要在Server Components中使用Zustand
  2. App Router的Context模式 - 避免全局状态存储(请求隔离)
  3. 对数组/对象使用useShallow - 防止不必要的重渲染
  4. 持久化时使用skipHydration - SSR兼容性的必要配置
  5. v5柯里化语法 -
    create<State>()((set) => ({...}))
  6. SOLID路径 - 状态存储放在
    modules/[feature]/src/stores/
    目录下

SOLID Architecture

SOLID 架构

Module Structure

模块结构

Stores organized by feature module:
  • modules/cores/stores/
    - Shared stores (theme, ui)
  • modules/auth/src/stores/
    - Auth state
  • modules/cart/src/stores/
    - Cart state
  • modules/[feature]/src/interfaces/
    - Store types
按功能模块组织状态存储:
  • modules/cores/stores/
    - 共享状态存储(主题、UI)
  • modules/auth/src/stores/
    - 认证状态
  • modules/cart/src/stores/
    - 购物车状态
  • modules/[feature]/src/interfaces/
    - 状态存储类型定义

File Organization

文件组织结构

FilePurposeMax Lines
store.ts
Store creation with create()50
store.interface.ts
TypeScript interfaces30
store-provider.tsx
Context provider (App Router)40
use-store.ts
Custom hook with selector20

文件用途最大行数
store.ts
使用create()创建状态存储50
store.interface.ts
TypeScript接口定义30
store-provider.tsx
Context提供者(App Router)40
use-store.ts
带选择器的自定义Hook20

Key Concepts

核心概念

Store Creation (v5 Syntax)

状态存储创建(v5语法)

Double parentheses required for TypeScript inference. Currying pattern ensures full type safety.
需要双括号以实现TypeScript类型推断。柯里化模式确保完整的类型安全。

Context-Based Stores

基于Context的状态存储

For Next.js App Router, wrap stores in Context to prevent request-sharing. Use
createStore
from
zustand/vanilla
with
useRef
for initialization.
对于Next.js App Router,将状态存储包装在Context中以避免请求共享。使用
zustand/vanilla
中的
createStore
结合
useRef
进行初始化。

Middleware Composition

中间件组合

Stack middlewares: devtools → persist → immer. Order matters for TypeScript types.
堆叠中间件:devtools → persist → immer。顺序对TypeScript类型有影响。

Hydration Handling

水合处理

Use
skipHydration: true
with persist middleware. Manually rehydrate in useEffect to avoid SSR mismatches.

在persist中间件中使用
skipHydration: true
。在useEffect中手动执行水合以避免SSR不匹配问题。

Reference Guide

参考指南

NeedReference
Initial setupinstallation.md
Store patternsstore-patterns.md
SSR/Hydrationhydration.md
Middlewaremiddleware.md
Next.js App Routernextjs-integration.md
TypeScripttypescript.md
Slices patternslices.md
Auto selectorsauto-selectors.md
Reset statereset-state.md
Subscribe APIsubscribe-api.md
Testingtesting.md
Migration v4→v5migration-v5.md

需求参考文档
初始设置installation.md
状态存储模式store-patterns.md
SSR/水合hydration.md
中间件middleware.md
Next.js App Router集成nextjs-integration.md
TypeScripttypescript.md
切片模式slices.md
自动选择器auto-selectors.md
重置状态reset-state.md
订阅APIsubscribe-api.md
测试testing.md
从v4迁移到v5migration-v5.md

Best Practices

最佳实践

  1. Selector pattern - Always use
    useStore((s) => s.field)
    for performance
  2. useShallow - Wrap array/object selectors to prevent re-renders
  3. Separate stores - One store per domain (auth, cart, ui, theme)
  4. Server data elsewhere - Use TanStack Query for server state
  5. DevTools in dev only - Wrap devtools in process.env check
  6. Partialize persist - Only persist necessary fields, never tokens

  1. 选择器模式 - 始终使用
    useStore((s) => s.field)
    以提升性能
  2. useShallow - 对数组/对象选择器使用useShallow包装以防止重渲染
  3. 分离状态存储 - 每个领域一个状态存储(认证、购物车、UI、主题)
  4. 服务端数据存放在别处 - 使用TanStack Query处理服务端状态
  5. 仅在开发环境使用DevTools - 在process.env检查中包装devtools
  6. 部分持久化 - 仅持久化必要字段,绝不持久化令牌

Forbidden Patterns

禁止模式

PatternReasonAlternative
Global stores in App RouterRequest sharing between usersContext-based stores
Zustand in Server ComponentsNo React hooks in RSCFetch data directly
Persisting auth tokensSecurity vulnerabilityhttpOnly cookies
Without useShallow on objectsExcessive re-renders
useShallow(selector)
v4 syntaxTypeScript inference brokenv5 currying
create<T>()()
模式原因替代方案
App Router中的全局状态存储用户之间的请求共享基于Context的状态存储
在Server Components中使用ZustandRSC中不支持React Hook直接获取数据
持久化认证令牌安全漏洞httpOnly Cookie
对对象不使用useShallow过度重渲染
useShallow(selector)
v4语法TypeScript类型推断失效v5柯里化语法
create<T>()()