React状态管理之Zustand

537 阅读1分钟

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

前言

1. Zustand 是什么?

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

2. 为什么选择 Zustand?

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

3.官方文档

zustand-demo.pmnd.rs/

安装

pnpm i zustand

使用

简易计数器

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

异步状态更新

首先模拟一个网络请求

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

create函数后添加action

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

调用请求:

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

持久化存储

导入presist中间件

import { persist,createJSONStorage } from 'zustand/middleware'

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

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

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