A selector is a function that picks the part of the state a component
needs: (s) => s.minutes. With a selector, useStore returns only that part,
and React re-renders the component only when that part changes.
npm install and npm run dev. Watch the console as you press Log 25 minutes, then Switch to Context.
What you'll see
Log 25 minutes logs only Minutes rendered. Switch to Context logs only Topic rendered. Each component re-renders for its own part, and no other.
How it works
export function useStore(store, selector = (state) => state) {
return useSyncExternalStore(store.subscribe, () => selector(store.getState()));
}After every store change, React calls the snapshot function again and compares
the result with the last one using Object.is. A number or string that didn't
change is equal, so the component is skipped.
The pitfall: a new object every time
Change Minutes to select an object:
const { minutes } = useStore(sessionStore, (s) => ({ minutes: s.minutes }));Run it.
What you'll see
The preview stays blank, and the console says The result of getSnapshot should be cached to avoid an infinite loop. The selector builds a new object on every call, so React never sees two equal snapshots: each check says "changed", which asks for another render, which builds another new object. React stops the loop instead of freezing the page.
Rules for selectors:
- Return something that's already in the state, or a primitive such as a number, string or boolean.
- Need several values? Call
useStoreonce for each, or keep a selector that returns an existing object from the state. - Need to compute something, such as a filtered list? Select the raw data,
then compute during render, with
useMemoif it's slow.
Libraries such as Zustand add a shallow comparison option for selecting
several fields. Underneath, it's this same rule.
Count the sessions
Add a Sessions component that shows 1 sessions logged, using a selector.
It must not re-render when you switch topic.
npm install and npm run dev. Hint 1: the idea
Subscribe to the smallest value the component displays. A change in an unrelated field should leave that snapshot equal.
Hint 2: a first step
Copy Minutes, select s.sessions, and log Sessions rendered to check.
Show one solution
function Sessions() {
const sessions = useStore(sessionStore, (s) => s.sessions);
console.log("Sessions rendered");
return <p className="muted">{sessions} sessions logged</p>;
}Add <Sessions /> next to <Minutes />. Switch to Context logs only
Topic rendered.
Completion is saved in this browser only. It does not measure mastery.