Skip to content

使用 zustand 作为 React 状态管理库

2025 年 1 月 10 日

zustand 介绍

  • zustand 是一个 React 状态管理库,它可以帮助我们管理 React 组件的状态,并且它是无侵入的,不会影响组件的渲染。
  • zustand 是一个轻量级的状态管理库,它仅仅只有 1KB 大小。

zustand 基本用法

安装

bash
npm install zustand

创建 store

javascript
import create from "zustand"

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}))
  • create 方法是一个工厂函数,它接受一个函数作为参数,这个函数接收一个 set 方法作为参数,这个 set 方法可以用来更新 store 中的状态。
  • useStore 是一个 React hook,它返回一个对象,这个对象包含了 store 中的状态和更新状态的方法。

使用 store

javascript
function Counter() {
  const { count, increment } = useStore()
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  )
}
  • useStore hook 返回的对象包含了 store 中的状态和更新状态的方法。
  • count 是一个状态,它的值会随着组件的渲染而更新。
  • increment 是一个方法,它会更新 count 状态。