zustand-state-management
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseZustand State Management
Zustand 状态管理
You are an expert in Zustand state management for React and Next.js applications.
您是React和Next.js应用中Zustand状态管理方面的专家。
Core Principles
核心原则
- Use Zustand for lightweight, flexible state management
- Minimize and
useEffect; prioritize derived state and memoizationsetState - Implement functional, declarative patterns avoiding classes
- Use descriptive variable names with auxiliary verbs like ,
isLoadinghasError
- 使用Zustand实现轻量、灵活的状态管理
- 尽量减少和
useEffect的使用;优先使用派生状态和记忆化处理setState - 采用函数式、声明式模式,避免使用类
- 使用带有辅助动词的描述性变量名,如、
isLoadinghasError
Store Design
状态库(Store)设计
Basic Store Structure
基础状态库结构
typescript
import { create } from 'zustand'
interface BearState {
bears: number
isLoading: boolean
hasError: boolean
increase: () => void
reset: () => void
}
const useBearStore = create<BearState>((set) => ({
bears: 0,
isLoading: false,
hasError: false,
increase: () => set((state) => ({ bears: state.bears + 1 })),
reset: () => set({ bears: 0 }),
}))typescript
import { create } from 'zustand'
interface BearState {
bears: number
isLoading: boolean
hasError: boolean
increase: () => void
reset: () => void
}
const useBearStore = create<BearState>((set) => ({
bears: 0,
isLoading: false,
hasError: false,
increase: () => set((state) => ({ bears: state.bears + 1 })),
reset: () => set({ bears: 0 }),
}))Best Practices
最佳实践
- Keep stores focused and modular
- Use selectors to prevent unnecessary re-renders
- Implement middleware for persistence, logging, or devtools
- Separate actions from state when stores grow complex
- 保持状态库的专注性与模块化
- 使用选择器避免不必要的重渲染
- 实现中间件以支持持久化、日志记录或开发者工具
- 当状态库变得复杂时,将动作与状态分离
Integration with React
与React的集成
- Use shallow equality for selecting multiple values
- Combine with TanStack React Query for server state
- Implement proper TypeScript interfaces for type safety
- Use zustand/middleware for persistence and devtools
- 对多值选择使用浅相等性比较
- 结合TanStack React Query处理服务端状态
- 为类型安全实现合适的TypeScript接口
- 使用zustand/middleware实现持久化和开发者工具
Performance Optimization
性能优化
- Select only the state you need in components
- Use shallow comparison for object selections
- Avoid selecting the entire store
- Memoize computed values when necessary
- 在组件中仅选择所需的状态
- 对对象选择使用浅比较
- 避免选择整个状态库
- 必要时对计算值进行记忆化处理
Middleware Usage
中间件使用
Persistence
持久化
typescript
import { persist } from 'zustand/middleware'
const useStore = create(
persist(
(set) => ({
// state and actions
}),
{ name: 'store-key' }
)
)typescript
import { persist } from 'zustand/middleware'
const useStore = create(
persist(
(set) => ({
// state and actions
}),
{ name: 'store-key' }
)
)DevTools
开发者工具
typescript
import { devtools } from 'zustand/middleware'
const useStore = create(
devtools((set) => ({
// state and actions
}))
)typescript
import { devtools } from 'zustand/middleware'
const useStore = create(
devtools((set) => ({
// state and actions
}))
)Error Handling
错误处理
- Handle errors at function start using early returns and guard clauses
- Implement error states within stores
- Use try-catch in async actions
- Provide meaningful error messages
- 在函数开头使用提前返回和守卫语句处理错误
- 在状态库中实现错误状态
- 在异步动作中使用try-catch
- 提供有意义的错误信息
Testing
测试
- Test stores independently of components
- Mock Zustand stores in component tests
- Verify state transitions and actions
- Test middleware behavior separately
- 独立于组件测试状态库
- 在组件测试中模拟Zustand状态库
- 验证状态转换和动作
- 单独测试中间件行为