一个小巧、快速且可扩展的基础状态管理解决方案,采用简化的 flux 原则。它具有基于钩子的舒适 API,不臃肿也不固执己见。
不要因为它看起来可爱就轻视它。它有相当强大的功能,花费了大量时间来处理常见的陷阱,如令人恐惧的僵尸子问题、React 并发和混合渲染器之间的上下文丢失。它可能是 React 生态系统中唯一一个正确处理所有这些问题的状态管理器。
你可以在这里尝试实时演示。
npm i zustand
:warning: 本说明文档是为 JavaScript 用户编写的。如果你是 TypeScript 用户,请务必查看我们的TypeScript 使用部分。
你的 store 是一个钩子!你可以在其中放置任何内容:原始类型、对象、函数。状态必须以不可变的方式更新,set
函数合并状态以帮助实现这一点。
import { create } from 'zustand' const useBearStore = create((set) => ({ bears: 0, increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), removeAllBears: () => set({ bears: 0 }), }))
在任何地方使用这个钩子,不需要提供者。选择你的状态,组件将在变化时重新渲染。
function BearCounter() { const bears = useBearStore((state) => state.bears) return <h1>这里有 {bears} 只熊...</h1> } function Controls() { const increasePopulation = useBearStore((state) => state.increasePopulation) return <button onClick={increasePopulation}>增加一只</button> }
你可以这样做,但请记住,这将导致组件在每次状态变化时更新!
const state = useBearStore()
默认情况下,它使用严格相等(old === new)检测变化,这对于原子状态选择来说是高效的。
const nuts = useBearStore((state) => state.nuts) const honey = useBearStore((state) => state.honey)
如果你想构造一个包含多个状态选择的单一对象,类似于 redux 的 mapStateToProps,你可以使用 useShallow 来防止选择器输出根据浅比较没有变化时的不必要重渲染。
import { create } from 'zustand' import { useShallow } from 'zustand/react/shallow' const useBearStore = create((set) => ({ bears: 0, increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), removeAllBears: () => set({ bears: 0 }), })) // 对象选择,当 state.nuts 或 state.honey 改变时重新渲染组件 const { nuts, honey } = useBearStore( useShallow((state) => ({ nuts: state.nuts, honey: state.honey })), ) // 数组选择,当 state.nuts 或 state.honey 改变时重新渲染组件 const [nuts, honey] = useBearStore( useShallow((state) => [state.nuts, state.honey]), ) // 映射选择,当 state.treats 的顺序、数量或键发生变化时重新渲染组件 const treats = useBearStore(useShallow((state) => Object.keys(state.treats)))
为了更好地控制重渲 染,你可以提供任何自定义的相等性函数。
const treats = useBearStore( (state) => state.treats, (oldTreats, newTreats) => compare(oldTreats, newTreats), )
set
函数有第二个参数,默认为 false
。它会替换状态模型而不是合并。请小心不要删除你依赖的部分,比如动作。
import omit from 'lodash-es/omit' const useFishStore = create((set) => ({ salmon: 1, tuna: 2, deleteEverything: () => set({}, true), // 清除整个 store,包括动作 deleteTuna: () => set((state) => omit(state, ['tuna']), true), }))
当你准备好时调用 set
,zustand 不关心你的动作是否是异步的。
const useFishStore = create((set) => ({ fishies: {}, fetch: async (pond) => { const response = await fetch(pond) set({ fishies: await response.json() }) }, }))
set
允许函数更新 set(state => result)
,但你仍然可以通过 get
在外部访问状态。
const useSoundStore = create((set, get) => ({ sound: 'grunt', action: () => { const sound = get().sound ...
有时你需要以非响应式的方式访问状态或对store进行操作。对于这些情况,生成的hook在其原型上附加了实用函数。
:warning: 不推荐在 React 服务器组件 中使用这种技术来添加状态(通常在 Next.js 13 及以上版本中)。这可能会导致意外的错误和用户隐私问题。更多详情请参见 #2200。
const useDogStore = create(() => ({ paw: true, snout: true, fur: true })) // 获取非响应式的最新状态 const paw = useDogStore.getState().paw // 监听所有变化,每次变化时同步触发 const unsub1 = useDogStore.subscribe(console.log) // 更新状态,将触发监听器 useDogStore.setState({ paw: false }) // 取消订阅监听器 unsub1() // 当然,你也可以像往常一样使用hook function Component() { const paw = useDogStore((state) => state.paw) ...
如果你需要使用选择器进行订阅,subscribeWithSelector
中间件会有所帮助。
使用这个中间件后,subscribe
接受一个额外的签名:
subscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubscribe
import { subscribeWithSelector } from 'zustand/middleware' const useDogStore = create( subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })), ) // 监听选定的变化,在这个例子中是当 "paw" 发生变化时 const unsub2 = useDogStore.subscribe((state) => state.paw, console.log) // subscribe 还会暴露前一个值 const unsub3 = useDogStore.subscribe( (state) => state.paw, (paw, previousPaw) => console.log(paw, previousPaw), ) // subscribe 还支持可选的相等性函数 const unsub4 = useDogStore.subscribe( (state) => [state.paw, state.fur], console.log, { equalityFn: shallow }, ) // 订阅并立即触发 const unsub5 = useDogStore.subscribe((state) => state.paw, console.log, { fireImmediately: true, })
Zustand 的核心可以在不依赖 React 的情况下导入和使用。唯一的区别是 create 函数不返回 hook,而是返回 API 实用工具。
import { createStore } from 'zustand/vanilla' const store = createStore((set) => ...) const { getState, setState, subscribe, getInitialState } = store export default store
你可以使用 v4 版本提供的 useStore
hook 来使用原生 store。
import { useStore } from 'zustand' import { vanillaStore } from './vanillaStore' const useBoundStore = (selector) => useStore(vanillaStore, selector)
:warning: 请注意,修改 set
或 get
的中间件不会应用于 getState
和 setState
。
subscribe 函数允许组件绑定到状态的一部分,而不会在变化时强制重新渲染。最好将其与 useEffect 结合使用,以在组件卸载时自动取消订阅。当你可以直接修改视图时,这可以产生显著的性能影响。
const useScratchStore = create((set) => ({ scratches: 0, ... })) const Component = () => { // 获取初始状态 const scratchRef = useRef(useScratchStore.getState().scratches) // 在挂载时连接到 store,在卸载时断开连接,在引用中捕获状态变化 useEffect(() => useScratchStore.subscribe( state => (scratchRef.current = state.scratches) ), []) ...
减少嵌套结构是令人疲惫的。你试过 immer 吗?
import { produce } from 'immer' const useLushStore = create((set) => ({ lush: { forest: { contains: { a: 'bear' } } }, clearForest: () => set( produce((state) => { state.lush.forest.contains = null }), ), })) const clearForest = useLushStore((state) => state.clearForest) clearForest()