Selectors: Subscribing to Specific Slices
What you'll learn: How to use selector functions with Zustand to prevent unnecessary re-renders when only part of your store changes.
The Problem: Over-Subscribing
When you consume Zustand state, every component re-renders whenever ANY part of the store changes—even if the component only cares about one tiny piece of data. Imagine subscribing to a newspaper just for the sports section, but having to read every page every day anyway.
The Solution: Selector Functions
Zustand hooks accept a selector function as an argument. This function extracts only the slice of state your component needs:
const bears = useStore(state => state.bears);
Now your component only re-renders when bears changes, not when other unrelated state updates.
Why This Matters
Without selectors, this component re-renders on every store change:
const AllState = () => {
const state = useStore(); // subscribes to EVERYTHING
return <div>{state.bears}</div>;
};
With a selector, it only re-renders when bears changes:
const JustBears = () => {
const bears = useStore(state => state.bears); // subscribes to bears only
return <div>{bears}</div>;
};
Multiple Slices
You can select multiple pieces—but they'll be compared shallowly:
const { bears, fish } = useStore(state => ({
bears: state.bears,
fish: state.fish
}));
Key Takeaway: Selector functions let you subscribe to specific slices of your Zustand store, preventing re-renders when unrelated state changes—making your app more performant by only updating components when their data actually changes.