React + Zustand 状态管理
React + Zustand 状态管理
📖 概述
Zustand 是一个轻量级、简单易用的 React 状态管理库,它提供了一种现代化的状态管理方式,无需复杂的样板代码。相比 Redux,Zustand 更加简洁,学习成本更低,但功能依然强大。
为什么选择 Zustand?
- 🚀 轻量级: 压缩后仅 2.9kb
- 🎯 简单易用: 最少的样板代码
- 💪 TypeScript友好: 完全支持 TypeScript
- 🔄 无Provider: 不需要包装组件
- ⚡ 性能优秀: 精准的重新渲染
- 🛠️ 开发工具: 支持 Redux DevTools
- 📦 持久化: 内置持久化中间件
🚀 安装
使用 npm
npm install zustand
使用 yarn
yarn add zustand
使用 pnpm
pnpm add zustand
🔧 基础用法
1. 创建基础 Store
import { create } from 'zustand'interface CounterState {count: numberincrement: () => voiddecrement: () => voidreset: () => void
}const useCounterStore = create<CounterState>((set) => ({count: 0,increment: () => set((state) => ({ count: state.count + 1 })),decrement: () => set((state) => ({ count: state.count - 1 })),reset: () => set({ count: 0 }),
}))
2. 在组件中使用
import React from 'react'
import { useCounterStore } from './stores/counterStore'const Counter: React.FC = () => {const { count, increment, decrement, reset } = useCounterStore()return (<div><h2>计数器: {count}</h2><button onClick={increment}>增加</button><button onClick={decrement}>减少</button><button onClick={reset}>重置</button></div>)
}export default Counter
3. 选择性订阅(性能优化)
// 只订阅 count 值,当其他状态变化时不会重新渲染
const CountDisplay: React.FC = () => {const count = useCounterStore((state) => state.count)return <div>当前计数: {count}</div>
}// 只订阅 increment 方法
const IncrementButton: React.FC = () => {const increment = useCounterStore((state) => state.increment)return <button onClick={increment}>+1</button>
}
🏗️ 高级用法
1. 异步操作
interface UserState {users: User[]loading: booleanerror: string | nullfetchUsers: () => Promise<void>createUser: (userData: CreateUserData) => Promise<void>
}const useUserStore = create<UserState>((set, get) => ({users: [],loading: false,error: null,fetchUsers: async () => {set({ loading: true, error: null })try {const response = await fetch('/api/users')const users = await response.json()set({ users, loading: false })} catch (error) {set({error: error instanceof Error ? error.message : '获取用户失败',loading: false})