Skip to main content

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

javascript
const count = useCounterStore((state) => state.count)

Here the component:

  • subscribes only to state.count;
  • will be re-rendered only when the value of count changes;
  • ignores all other changes in the store.

Example - the difference between a "non-selective" and a "selective" approach

Bad (non-selective)

javascript
const { count, user } = useStore()

The component re-renders even if user changes, even though it only cares about count.


Good (selective)

javascript
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:

  1. Zustand calls selector(state) and saves the result.
  2. When the state changes, Zustand compares the new value returned by the selector with the old one.
  3. 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:

javascript
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

ConceptDescription
SelectorA function (state) => part of the state that defines what the component listens to
SelectivityThe component receives only the data it needs and reacts only to its change
AdvantageNo unnecessary re-renders, high performance
shallowShallow comparison for complex objects

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.