CodePark/ questions / State management
START PRACTICINGPRACTICE
Frontend question · React › State management

Why can a store like Zustand or Redux avoid the re-render problem that a single large Context has? What React API do they use?

Stores like Zustand and Redux let each component subscribe to only the part of the state it uses. They connect to React with useSyncExternalStore.

With context, every consumer re-renders when the provider value changes. There is no built-in way to subscribe to only part of the value.

An external store keeps state outside React. Components subscribe with a selector, a function that picks the part they need, like useStore(s => s.cart.count). When the store changes, each subscriber runs its selector. It compares the result with the previous one. Only components whose selected part actually changed re-render.

useSyncExternalStore(subscribe, getSnapshot) works like this:

  • React calls subscribe to listen for changes.
  • React calls getSnapshot to read the current value, and re-renders when the snapshot changes.

It also keeps reads consistent during concurrent rendering. This avoids tearing, where different components show different versions of the same store at once.

Snapshots must be stable. getSnapshot must return the same cached value while the store has not changed. If it returns a new object each time, React thinks the data changed and loops forever.

  • Context has no way to subscribe to only part of the value.
  • Stores live outside React, and components subscribe with selectors.
  • Only components whose selected part changed re-render.
  • Stores are built on useSyncExternalStore(subscribe, getSnapshot).
  • It prevents tearing in concurrent rendering.
  • getSnapshot must return the same value while the store is unchanged, or React loops.