Zustand subscribe selector execution frequency and reference stability
0 reputation · 15 May 2023, 21:54 UTC
Zustand's subscribe function allows for transient state updates by listening to changes outside the React render cycle. When using a selector to isolate specific state slices, the callback is triggered based on the result of that selector.
There is uncertainty regarding how the subscription mechanism handles selectors that return new object references or computed values on every state change, even if the underlying data remains logically equivalent. If a selector returns a new object literal, it may trigger the subscription callback regardless of whether the actual values changed.
- Does the
subscribemethod perform a shallow comparison on the selector's return value before executing the callback? - What is the recommended approach to ensure a subscription only fires when specific nested properties change without manually implementing a deep comparison inside the callback?