【JS 第三方库】Zustand 我愿称之为 React 中最简单的状态管理库

2026-04-28 19:26:59

React 中流行的状态管理有 Context API、Redux,国内比较出名的有 Dva,现在我又知道一个极其简单的状态库叫做 Zustand。

安装依赖:

$ npm install zustand

不需要什么集成配置,安装完直接就用。

import { create } from 'zustand'

// 使用 create 函数创建 Store
const useTheme = create((set) => ({
  theme: 'white', // 初始状态
  updateTheme: (theme: string) => set(() => ({ theme })), // 更新状态
  count: 1,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
}))

export function App() {
  const { theme, updateTheme, count, increment, decrement } = useTheme()

  const onThemeUpdated = (color: string) => {
    updateTheme(color)
  }

  return (
    <div style={{ backgroundColor: theme, height: '100vh' }}>
      <div>
        <button onClick={() => onThemeUpdated('red')}>Red</button>
        <button onClick={() => onThemeUpdated('green')}>Green</button>
      </div>

      <div>
        <span>{count}</span>
        <button onClick={increment}>Increment</button>
        <button onClick={decrement}>Decrement</button>
      </div>
    </div>
  )
}

export default App

状态管理的数据是存在当前标签页的内存里,刷新页面时会重置状态管理中的变量值。如果想将变量值持久化,通常需要手动写代码与 localStorage 进行交互,包含存数据和取数据,如果变量值是数组或对象字面量还需要序列化为字符串再处理,总之很麻烦。

zustand 提供 persist API 可以简化这一过程,如下示例,可以看到 user 是个对象字面量也可以轻松持久化,打开浏览器控制台 -> Application -> Local storage,可以看到数据是有保存的。

import { create } from 'zustand'
import { persist } from 'zustand/middleware'

// 使用 create 函数创建 Store
const useUserInfo = create(
  persist(
    // 第一个参数:定义状态和方法的函数
    (set) => ({
      user: { name: 'dkvirus' },
      updateUser: (name: string) => set(() => ({ user: { name } }))
    }),
    // 第二个参数:持久化配置对象
    {
      name: 'my-storage-key', // 存储在 localStorage 中的键名(必填)
    }
  )
);

export function App() {
  const { user, updateUser } = useUserInfo()

  return (
    <div>
      <div>
        {user.name}
      </div>
      <button onClick={() => updateUser('god')}>
        修改名称
      </button>
    </div>
  )
}

export default App

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: