External Stores and Selectors
Worked example: build a module-level store, subscribe with useSyncExternalStore, slice it with selectors — and see where Zustand takes over from the hand-rolled version.
Contentsand lesson path
On this page
- The problem
- Step 1: a store in twenty lines
- Step 2: subscribe with useSyncExternalStore
- Step 3: the snapshot rule, learned the hard way
- Step 4: the same shape, maintained — Zustand
- When a store, when context
- Check your understanding
- Apply it
- Review prompt
Lessons of Frontend State Management
- Where Should This State Live? Concept · 20 min
- Reducers for Complex Transitions Worked example · 25 min
- Context Without the Re-render Tax Concept · 20 min
- External Stores and Selectors Worked example · 25 min
- Lab: Untangle a Prop-Drilled Cart Lab · 30 min
- Check: State Placement Scenarios Knowledge check · 6 questions
What you will learn
- Implement global client state with an external store such as Zustand or Redux Toolkit using selectors, and explain when a store is warranted over context.
Prerequisites: React Components & State
01. The problem
Context has no mechanism for "tell me only when my slice changes". Every consumer of a context re-renders when the value changes, so the tax grows with the number of readers and the frequency of updates — exactly the two things that grow in real products. An external store inverts the flow: the state lives in a plain module, outside React, and each component subscribes to it with a selector — a function that picks the slice it cares about. React compares the selected slice with the previous one and re-renders the component only when that slice actually changed.
This worked example builds the smallest honest version: a store in twenty lines, wired to React with useSyncExternalStore, then the same shape as the ecosystem ships it in Zustand. Every render count and error below was observed by running the components under Testing Library; the versions were React 19.3.1, Zustand 5.1.0 and, for the Redux comparison, react-redux 9.3.1.
02. Step 1: a store in twenty lines
type Listener = () => void;
export function createStore<T>(initial: T) {
let state = initial;
const listeners = new Set<Listener>();
return {
getState: () => state,
setState: (next: T | ((prev: T) => T)) => {
const value =
typeof next === 'function' ? (next as (prev: T) => T)(state) : next;
if (Object.is(value, state)) return; // same reference: nothing to do
state = value;
for (const listener of listeners) listener();
},
subscribe: (listener: Listener) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
};
}That is the whole contract: read with getState, write with setState, listen with subscribe. Two details carry the pattern. The Object.is guard makes an update that returns the same reference a no-op — a test that sets the identical object and an updater returning prev both produced zero notifications when run. And the state lives in a closure in a module, not in React: any code, React or not, can read it, which is why stores reach across pages without a provider wrapping the tree.
03. Step 2: subscribe with useSyncExternalStore
import { useSyncExternalStore } from 'react';
import { createStore } from './store';
export type Cart = { items: string[]; lastAdded: string | null };
export const cartStore = createStore<Cart>({
items: [],
lastAdded: null,
});
export function addItem(name: string): void {
cartStore.setState((prev) => ({
items: [...prev.items, name],
lastAdded: name,
}));
}
export function useCartSlice<T>(selector: (cart: Cart) => T): T {
return useSyncExternalStore(
cartStore.subscribe,
() => selector(cartStore.getState()),
);
}useSyncExternalStore takes the store's subscribe and a getSnapshot function — here the selector run against the current state. On every store notification React calls getSnapshot and compares the result with the last value it saw; equal means no render. Two components with different selectors over the same store therefore hear different amounts of news. Badge selects items.length; LastAdded selects lastAdded. Add Bagels twice and watch:
render Badge
render LastAdded
render Badge
render LastAdded
render BadgeMount renders both. The first add changes both slices — count 0 to 1, lastAdded null to 'Bagels' — so both re-render. The second add pushes the same name: the count changes again, but lastAdded is 'Bagels' to 'Bagels', Object.is says equal, and LastAdded stays quiet. That is the selector subscription doing precisely what context cannot.
04. Step 3: the snapshot rule, learned the hard way
The contract has one sharp edge: getSnapshot must return a stable value — the same reference while nothing changed. A selector that builds a new object or array on every call breaks it:
// Broken: a fresh object on every call.
useSyncExternalStore(cartStore.subscribe, () => ({
count: cartStore.getState().items.length,
}));
// Fine: the array itself keeps its reference until the state changes.
useSyncExternalStore(cartStore.subscribe,
() => cartStore.getState().items,
);console.error: The result of getSnapshot should be cached to avoid an infinite
loop
Error: Maximum update depth exceeded. This can happen when a component
repeatedly calls setState inside componentWillUpdate or componentDidUpdate. …Both lines were produced by really rendering that component: React logs the caching warning and then aborts with "Maximum update depth exceeded", because every snapshot "differs" from the last and the update loop never settles. The rule to internalise: select a value that already exists in the store, or memoise a derived object so its identity survives between changes. Selector libraries encode this: Zustand compares with Object.is by default and throws "Maximum update depth exceeded" in v5 if a selector returns a new object on every render without useShallow, whereas Redux's useSelector (react-redux 9) does not crash — it logs a development warning ("Selector unknown returned a different result...") and causes unnecessary re-renders.
05. Step 4: the same shape, maintained — Zustand
import { create } from 'zustand';
type Cart = { items: string[]; voucher: string | null };
type Actions = {
add: (name: string) => void;
setVoucher: (voucher: string) => void;
};
export const useCart = create<Cart & Actions>()((set) => ({
items: [],
voucher: null,
add: (name) => set((state) => ({ items: [...state.items, name] })),
setVoucher: (voucher) => set({ voucher }),
}));
// In a component: subscribe to one slice.
const count = useCart((s) => s.items.length);Zustand is the hand-rolled store with the rough edges sanded: no provider, actions living beside the state, and per-component selector subscriptions. Measured behaviour, one store read by three components — Badge selecting items.length, Voucher selecting voucher, and Everything calling the hook with no selector. Apply a voucher, then add two items:
render Badge
render Voucher
render Everything
render Voucher
render Everything
render Badge
render Everything
render Badge
render EverythingThe voucher change never touched Badge: its selector returned a length that had not changed, so it did not re-render. Each add then skipped Voucher the same way. Everything — no selector — re-rendered for every change, which is the honest cost of subscribing to the whole store. Redux Toolkit, the other mainstream option, works on the same selector principle with useSelector; it brings a larger toolkit (devtools, middleware, slices) that earns its size on bigger applications — the syllabus reference in Redux Toolkit is the place to compare. What matters here is that the mechanism is the one you just built: module state, subscriptions, selectors, reference comparison.
06. When a store, when context
The choice is about change rate and slice variety, not fashion. Reach for a store when shared state changes often and different components read different slices of it — a cart, an editor document, live UI preferences — because selector subscriptions are the only mechanism on offer that re-renders by slice. Stay with context when state changes rarely and consumers broadly agree on what they need — theme, locale, the signed-in user. Keep URL state in the URL, and server data in a cache (the query cache lab); neither belongs in either container. And hold the line from lesson 1: colocate first, derive second, share only what is genuinely shared. The lab uses all four homes in one app — reducer in context for the cart, URL for filters, a hand-rolled store for a cross-page preference — and records why each went where.
07. Check your understanding
08. Apply it
Build the currency store from the lab in your own project, or promote one piece of prop-drilled state to a module store. Add a render counter to two consumers with different selectors, drive five store updates, and write down which consumers re-rendered and why. Then try the same value through context and compare — the practice brief asks for exactly this documented comparison for the cart's cross-page preference.
09. Review prompt
Without looking back: write the three methods of createStore from memory, state the two arguments of useSyncExternalStore, and explain — in one sentence each — why the same-reference guard matters, why a fresh-object selector crashes, and when a store beats context.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.