157 - 《手撕源码 20:zustand》
发布于 2022年7月27日
zustand 昨天(2022.7.26)发布了 4.0,趁这个机会翻翻源码。
zustand 目前的维护者是 Daishi Kato,应该很多人都很熟悉吧。Github ID dai-shi,自由职业者,来自日本,状态库大师。除了 zustand,valtio、jotai、react-tracked、use-context-selector 等也都出自他手。他今年还写了本书《Micro State Management with React Hooks》和录制了 EggHead 的视频《Complex State Management in React with Jotai and XState》。
zustand 是和 redux、dva 类似的数据流方案,都属于 immutable state 的数据流。但相比来说,zustand 在 TypeScript 方面支持地更好。
先看使用方式。
// 1、定义 store
const useCountStore = create(set => ({
count: 0,
add: () => set(state => ({ count: state.count + 1 })),
});
// 2.1、hook 方式使用 store
const { cont, add } = useCountStore();
// 2.2