没有样板代码,没有额外学习成本,简单清晰,上手即用,配合 Immer 可使语句更简便。
支持中间件,比如很方便地将全局状态同步到 localStorage 缓存中。
https://www.npmjs.com/package/zustand
基础使用
定义:
import { create } from "zustand";
type SidebarStore = {
isOpen: boolean;
onOpen: () => void;
onClose: () => void;
};
export const useSidebar = create<SidebarStore>((set) => ({
isOpen: false,
onOpen: () => set({ isOpen: true }),
onClose: () => set({ isOpen: false }),
}));
在 React 组件中使用:
const onOpen = useSidebar((state) => state.onOpen);
const onClose = useSidebar((state) => state.onClose);
const isOpen = useSidebar((state) => state.isOpen);
配合 immer 使用
通过 immer 的 produce 减少对象操作嵌套:
import { produce } from 'immer'
const useLushStore = create((set) => ({
lush: { forest: { contains: { a: 'bear' } } },
clearForest: () =>
set(
produce((state) => {
state.lush.forest.contains = null
}),
),
}))
也可以配合 immer 中间件使用:
https://docs.pmnd.rs/zustand/integrations/immer-middleware
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
export const useCountStore = create()(
immer((set) => ({
count: 0,
increment: (qty) =>
set((state) => {
state.count += qty
}),
decrement: (qty) =>
set((state) => {
state.count -= qty
}),
})),
)
使用 localStorage 中间件
https://docs.pmnd.rs/zustand/integrations/persisting-store-data
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
const useFishStore = create(
persist(
(set, get) => ({
fishes: 0,
addAFish: () => set({ fishes: get().fishes + 1 }),
}),
{
name: 'food-storage', // 存储中项目的名称(必须唯一)
storage: createJSONStorage(() => localStorage),
},
),
)