3月7日 12:01
如何在 Zustand 中优化状态更新和性能?
Zustand 中的性能优化方法:
- 选择性订阅:
javascript// 不推荐:订阅整个 store,会导致组件在任何状态变化时都重渲染 const { count, user } = useStore(); // 推荐:只订阅需要的状态部分 const count = useStore((state) => state.count); const user = useStore((state) => state.user);
- 使用 shallow 比较(对于复杂对象):
javascriptimport { create } from 'zustand'; import { shallow } from 'zustand/shallow'; // 订阅多个状态并使用 shallow 比较 const { count, user } = useStore( (state) => ({ count: state.count, user: state.user }), shallow // 只有当 count 或 user 真正变化时才重渲染 );
- 状态拆分:
javascript// 按功能拆分多个 store // userStore.js const useUserStore = create((set) => ({ user: null, setUser: (user) => set({ user }) })); // counterStore.js const useCounterStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })) }));
- 使用 get 访问当前状态(避免闭包陷阱):
javascriptconst useStore = create((set, get) => ({ count: 0, // 推荐:使用 get 获取最新状态 increment: () => set((state) => ({ count: state.count + 1 })), // 也可以使用 get incrementAsync: async () => { await someAsyncOperation(); set({ count: get().count + 1 }); } }));
- 批量更新:
javascript// Zustand 会自动批量处理多个 set 调用 const updateMultiple = () => { set({ count: 1 }); set({ user: { name: 'John' } }); // 只会触发一次重渲染 };
- 避免在组件渲染时创建新函数:
javascript// 不推荐:每次渲染都创建新函数 const incrementBy = (value) => useStore.getState().incrementBy(value); // 推荐:在 store 中定义方法 // 在 store 中: incrementBy: (value) => set((state) => ({ count: state.count + value })) // 在组件中: const incrementBy = useStore((state) => state.incrementBy);
关键点:
- 选择性订阅是 Zustand 性能优化的核心
- 使用 shallow 比较可以优化复杂对象的订阅
- 状态拆分可以减少不必要的重渲染
- 合理使用 get 可以避免闭包陷阱
- Zustand 会自动处理批量更新