服务端阅读 02026年5月30日 01:39
如何优化 Zustand 状态更新性能?
Zustand 性能优化先看订阅粒度:组件只订阅自己需要的字段,不要 useStore() 拿整个 store。多个字段一起取时用 shallow 或拆成多个 selector;状态太大时按领域拆 store;异步更新用函数式 set 或 get() 避免旧值。真正的瓶颈通常不是 Zustand,而是选择器返回新对象、组件订阅过宽、列表渲染太重。追问为什么 useStore() 容易造成重渲染?它订阅整个 store,任何字段变化都会让组件重新渲染。字段越多,误伤越明显。shallow 能解决什么问题?selector 返回对象或数组时,每次都是新引用。shallow 会比较第一层字段,字段没变就不触发更新。拆 store 一定更好吗?不一定。强相关状态放一起更好维护;变化频率差异很大、业务边界清楚时再拆,否则会增加同步成本。批量更新要手动处理吗?React 18 下大多数场景会自动批处理。更重要的是把相关字段放在一次 set 里,避免中间状态被订阅者看到。写段代码import { shallow } from 'zustand/shallow';const count = useStore((s) => s.count);const inc = useStore((s) => s.inc);const userView = useStore( (s) => ({ name: s.user.name, role: s.user.role }), shallow);const useStore = create((set) => ({ count: 0, inc: () => set((s) => ({ count: s.count + 1 }))}));