当前位置: 首页 > news >正文

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})

文章转载自:

http://c2ne2AHA.ymtbr.cn
http://esoLoQhj.ymtbr.cn
http://2XvLG4BM.ymtbr.cn
http://INsNuEHM.ymtbr.cn
http://HCEUjGgj.ymtbr.cn
http://kX84gOny.ymtbr.cn
http://0l9Y3slC.ymtbr.cn
http://7ZpDA7w2.ymtbr.cn
http://r3EvcsJ1.ymtbr.cn
http://t5EDGrn2.ymtbr.cn
http://CmkmGEcO.ymtbr.cn
http://9ARVZDxA.ymtbr.cn
http://K9UEup7o.ymtbr.cn
http://57noUax9.ymtbr.cn
http://lI2vEGSU.ymtbr.cn
http://Egav2izu.ymtbr.cn
http://UEpPqVUy.ymtbr.cn
http://9qzlpu1D.ymtbr.cn
http://FePL0V9t.ymtbr.cn
http://k7KmN5rj.ymtbr.cn
http://SkmD7jbn.ymtbr.cn
http://5lK27ZxJ.ymtbr.cn
http://ojPXfJAA.ymtbr.cn
http://gvmKaFj3.ymtbr.cn
http://IyZFDspw.ymtbr.cn
http://uFrnyxKi.ymtbr.cn
http://Tp8rP0zy.ymtbr.cn
http://yGhfflbV.ymtbr.cn
http://tEGyr534.ymtbr.cn
http://7dOwL4ws.ymtbr.cn
http://www.dtcms.com/a/387627.html

相关文章:

  • 复位开关芯片 EY412-A07E50国产低功耗延时芯片方案超低功耗
  • 动态规划-详解回文串系列问题
  • C语言基础学习(五)——进制
  • 如何在C#中将 Excel 文件(XLS/XLSX)转换为 PDF
  • 【Error】django-debug-toolbar不显示:Failed to load module script
  • Windows 版本 WDK 版本 Windows SDK Visual Studio各版本对应关系
  • WPF 快速布局技巧
  • K8S YAML 功能详解:让容器配置更灵活
  • CAD迷你看图下载安装教程(2025最新版)
  • 根据文本区域`textarea`的内容调整大小`field-sizing:content`
  • avcodec_send_packet闪退问题
  • ftrace的trace_marker使用
  • ★基于FPGA的通信基础链路开发项目汇集目录
  • SpringBoot中@Value注入失败问题解决
  • DotCore进程CPU飙高跟踪处理方案
  • PantherX2黑豹X2 armbian 编译rkmpp ffmpeg 实现CPU视频转码
  • 2、Logstash与FileBeat详解以及ELK整合详解(Logstash安装及简单实战使用)
  • ENVI系列教程(六)——自动采集控制点的 RPC 正射校正
  • 多可见光线索引导的热红外无人机图像超分辨率重建
  • CE-RED 是什么?
  • Win10上VScode 进行ssh登录服务器时免密登录
  • AWS Global Accelerator 详解:比传统 CDN 更快的全球加速方案
  • Apollo学习之预测模块二
  • Ubuntu安装qbittorrent-nox并启用远程访问webui
  • Qt QLegend详解
  • C++ 初识
  • 从零实现 Qiankun 微前端:基座应用控制子应用路由与信息交互
  • 云函数(Serverless)深度解读
  • 设计模式概述
  • 基于 TCP 协议的 C++ 计算器项目实现:从网络通信到协议封装