React状态管理之Zustand

相信许多小伙伴学习React的时候,接触的第一个状态管理库是Redux,但是这个库有非常多的钩子函数,非常难记,偶然发现一个Zustand库,对开发者非常友好。

前言

1. Zustand 是什么?

Zustand 是一个轻量级、灵活且直观的 React 状态管理库。相较于 Redux,它的 API 更简单,减少了样板代码,并提供了良好的开发体验。Zustand 适用于管理全局状态,特别适合小型或中型项目。

2. 为什么选择 Zustand?

  • 简单易用:只需几行代码即可创建状态存储。
  • 无样板代码 :不需要像 Redux 那样定义 reduceraction,直接操作 state
  • 性能优秀 :采用浅比较和 React.useSyncExternalStore,避免不必要的重新渲染。
  • 支持中间件 :提供 persistdevtoolsimmer 等中间件,扩展性强。

3.官方文档

zustand-demo.pmnd.rs/

安装

bash 复制代码
pnpm i zustand

使用

简易计数器

ts 复制代码
import { create } from 'zustand'

type Store = {
  count: number
  inc: () => void
}

const useStore = create<Store>()((set) => ({
  count: 1,
  inc: () => set((state) => ({ count: state.count + 1 })),
}))

function Counter() {
  const { count, inc } = useStore()
  return (
    <div>
      <span>{count}</span>
      <button onClick={inc}>one up</button>
    </div>
  )
}

异步状态更新

首先模拟一个网络请求

ts 复制代码
const fetchMockCount = (delay: number): Promise<number> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 模拟异步请求返回固定值
      resolve(666);
    }, delay);
  });
};

create函数后添加action

ts 复制代码
const useStore = create<Store>()((set) => ({
  ...
  // 添加异步函数
  fetchAsyncCount: async (delay: number) => {
    try {
      const data = await fetchMockCount(delay);
      set({ count: data });
    } catch (error) {
      console.error("Failed to fetch count:", error);
    }
  }
}))

调用请求:

ts 复制代码
const { fetchAsyncCount } = useCountStore();
function Test() {
  return (
    <>
      <button onClick={() => fetchAsyncCount(1000)}>获取异步数据</button>
    </>
  );
}

持久化存储

导入presist中间件

ts 复制代码
import { persist,createJSONStorage } from 'zustand/middleware'

将之前create函数后的(set)=>void放入presist中间件中

ts 复制代码
create<Store>()(
	persist((set)=>{
        // 一些逻辑
        count: 0,
        increase(){
            
        },
    },{
        name: "countStorage",
        storage: createJSONStorage(() => sessionStorage),
    })
)

storage不填写默认为localStorage,可自定义为sessionStorage

相关推荐
共享家95275 小时前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Halo_tjn6 小时前
基于封装的专项 知识点
java·前端·python·算法
摘星编程7 小时前
OpenHarmony环境下React Native:自定义useTruncate文本截断
javascript·react native·react.js
Duang007_7 小时前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
2601_949868368 小时前
Flutter for OpenHarmony 电子合同签署App实战 - 主入口实现
开发语言·javascript·flutter
m0_748229998 小时前
Vue2 vs Vue3:核心差异全解析
前端·javascript·vue.js
C澒9 小时前
前端监控系统的最佳实践
前端·安全·运维开发
xiaoxue..9 小时前
React 手写实现的 KeepAlive 组件
前端·javascript·react.js·面试
摘星编程9 小时前
在OpenHarmony上用React Native:自定义useHighlight关键词高亮
javascript·react native·react.js
hhy_smile9 小时前
Class in Python
java·前端·python