Subscribing to a field in Zustand
Zustand hooks are called "selective hooks" because they let a component subscribe not to the whole store, but only to the specific pieces of state it actually needs.
This is one of the key reasons Zustand is considered a very performant and minimalistic state manager.
What "selective access" means
In ordinary global state (for example, through the Context API or a Redux Provider), a component subscribes to the entire state, even if it uses only one field. As a result, any change anywhere in the store causes unnecessary re-renders.
Zustand solves this with selectors
const count = useCounterStore((state) => state.count)Here the component:
- subscribes only to
state.count; - will be re-rendered only when the value of
countchanges; - ignores all other changes in the store.
Example - the difference between a "non-selective" and a "selective" approach
Bad (non-selective)
const { count, user } = useStore()The component re-renders even if user changes, even though it only cares about count.
Good (selective)
const count = useStore((state) => state.count)Now the component will react only to changes in count.
Under the hood
When you call the useStore(selector) hook:
- Zustand calls
selector(state)and saves the result. - When the state changes, Zustand compares the new value returned by the selector with the old one.
- If it has not changed, the component does not re-render.
Thanks to this, Zustand's mechanism stays:
- as fast as possible (re-renders only when truly necessary);
- simple to use (no manual memoization);
- type-safe when working with TypeScript.
Advanced capabilities
Zustand also lets you use deep selectors with shallow comparison (shallow) to prevent false re-renders:
import { shallow } from 'zustand/shallow'
const { count, increase } = useCounterStore(
(state) => ({ count: state.count, increase: state.increase }),
shallow // comparison by value, not by reference
)Now the component will not re-render if count and increase have not changed.
Summary
| Concept | Description |
|---|---|
| Selector | A function (state) => part of the state that defines what the component listens to |
| Selectivity | The component receives only the data it needs and reacts only to its change |
| Advantage | No unnecessary re-renders, high performance |
| shallow | Shallow comparison for complex objects |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.