Skip to main content

全局状态管理 zustand

Zustand 是一个 轻量级、直观的 React 状态管理库,由 Poimandres 团队 开发,作者也参与了著名的 react-three-fiber 等项目。Zustand 的设计目标是简单、灵活,并避免了 React 组件间复杂的状态传递和性能问题。


🧪 基础使用示例

import React from 'react';

import { useGlobalStore } from '@/store';
import { prevState } from '@/store/init';

function Index() {
const theme = useGlobalStore((state) => state.theme);
//框架内自定义函数 可以同时设置多个状态
const setState = useGlobalStore((state) => state.setState);

useEffect(() => {
//根据业务设置状态值
setState({ theme: 'dark' });
}, []);

//初始化
useLayoutEffect(() => {
//初始化预设状态
setState({ ...prevState });
}, []);

return <div>{theme}</div>;
}

🧪 Action

如果同一个接口很多组件内都需要调用,那么只需在 zustand 内定义一次即可灵活调用。

📚 定义 src/store/index.ts

import { message } from "@npmqg/utils-message";

import { requestChatList } from "@/services/public";

// 创建 Zustand Store,并添加持久化功能
export const useGlobalStore = create<GlobalState & GlobalActions>()(
persist(
immer((set) => ({
...baseState,

// 异步获取聊天列表
fetchChatList: async () => {
try {
const res = await requestChatList();
const historyDialogList = res.data?.map((item: any, index: number) => ({
...item,
key: `${Math.floor(Math.random() * 1000000000)}-${index}`,
data: item.data?.map((el: any) => ({ ...el, active: false }))?.reverse(),
}));
set({ historyDialogList });
} catch (err) {
console.error('fetchChatList error:', err);
}
},
})),
),
);

📚 组件内使用示例

import React from 'react';

import { useGlobalStore } from '@/store';

function Index() {
const historyDialogList = useGlobalStore((state) => state.historyDialogList);
const fetchChatList = useGlobalStore((state) => state.fetchChatList);

useEffect(() => {
fetchChatList().then();
}, []);

return (
<div>
{/* 渲染 fetchChatList 获取的结果状态 */}
{historyDialogList}
</div>
);
}

✨ 使用说明

  • 初始状态:export const state 用户第一次进入页面的默认值
  • 预设状态:export const prevState 每次刷新页面的预定义值

清除缓存就是要把状态还原为初始状态,在清除缓存时可以指定忽略的还原的状态 key。

src/store/index.ts

//向数组内添加不参与缓存清理的状态
const noClearState = ['token'];

🧬 Zustand 适用场景

  • 替代 Redux/Context,简化全局状态管理
  • 用于组件之间共享状态(如弹窗状态、用户信息)
  • 多 store 管理(更灵活的模块化结构)

🧠 核心特点

  • 无 Provider:不像 Redux 或 Context API,不需要额外的 Provider 组件。
  • 原子化状态:每个 store 独立管理,按需使用。
  • 高性能:只触发使用了状态的组件更新,避免不必要的渲染。
  • 支持中间件:如 devtoolspersistimmer 等,增强功能。
  • TypeScript 支持优秀:类型推导自然清晰。

✅ 与其他库比较

特性ZustandReduxRecoilJotai
易用性⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
文件结构复杂度⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
性能⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
中间件生态⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
学习成本⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐