Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 2

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

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

TypeScript · store.ts
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

TSX · cart-store.ts
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:

Expected output · render log (mount, add, add)
render Badge
render LastAdded
render Badge
render LastAdded
render Badge

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

TSX · a selector that must not be shipped
// 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,
);
Expected output · rendering the broken selector (wrapped; the error message is cut)
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

TSX · with zustand (npm install [email protected])
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:

Expected output · render log (mount, voucher, add, add)
render Badge
render Voucher
render Everything
render Voucher
render Everything
render Badge
render Everything
render Badge
render Everything

The 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

Practice check · 3 questions

Selector subscriptions

Three predictions about the stores built in this lesson.

Q1. A store holds `{ items, coupon }`. `Badge` selects `s.items.length`; `Voucher` selects `s.coupon`. An action updates only `coupon`. Who re-renders?
Q2. Two selectors over one store: A returns `s.filters` (the stored array); B returns `s.items.filter((i) => i.done)` computed inline. Which is safe as a getSnapshot?
Q3. A currency preference is read on three pages that sit under different layouts. What does a module-level store give you here that context does not?
Practice only: not graded, not saved, not evidence.

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.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check