react Zustand 详细使用
2026/5/10 5:39:21 网站建设 项目流程

下面给你一份React + Zustand 的系统性、从入门到进阶的使用指南,按实际项目节奏来讲,基本覆盖 90% 场景。


一、Zustand 是什么 & 为什么用它

Zustand是一个:

  • ✅ 极简(1KB)
  • ✅ 基于 Hook
  • ✅ 无需 Provider
  • ✅ TypeScript 友好
  • ✅ 可直接写异步逻辑

的状态管理库,常用于:

  • 跨组件共享状态
  • 替代 Redux / MobX
  • 中小型 React / Next.js 项目

二、安装

npminstallzustand# 或pnpmaddzustand

三、最基础用法(必会)

1️⃣ 创建 Store

// stores/counterStore.tsimport{create}from'zustand';typeCounterState={count:number;increment:()=>void;decrement:()=>void;reset:()=>void;};exportconstuseCounterStore=create<CounterState>((set)=>({count:0,increment:()=>set((state)=>({count:state.count+1})),decrement:()=>set((state)=>({count:state.count-1})),reset:()=>set({count:0}),}));

set用于修改状态
✅ 不需要 action / dispatch


2️⃣ 在组件中使用

import { useCounterStore } from './stores/counterStore'; function Counter() { const count = useCounterStore((state) => state.count); const increment = useCount

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询