The last chapter sorted state into kinds and found that, once server data, URL state, form drafts and derived values have their proper homes, a small amount of genuinely shared client state is left. This chapter is about where that goes.
You already have one answer: context. It works, and for values that change rarely it's the right answer. But context has a cost that grows with how often the value changes and how many components read it, and concurrent rendering adds a second, subtler problem called tearing. Both are fixed by the same idea: an external store, a plain JavaScript object outside React that components subscribe to with a selector.
We'll build one from scratch in about forty lines: createStore, a useStore(selector) hook on top of useSyncExternalStore, and the equality check that makes object selectors safe. This toy is the reference model for the rest of Part 6. Redux, Zustand and Jotai are all variations on it, and each of their chapters maps its API back to the pieces you build here. If you understand this chapter, you can explain any of them in an interview.
The problem: context re-renders every consumer#
Here's a small app state in context: which books are selected, and a theme. Three components consume it, each wrapped in memo, and each reads a different part. Select a book and watch the render counts.
import { createContext, memo, useContext, useMemo, useState } from "react";
import { books, Rendered } from "guide-tools";
type AppState = { selected: number[]; theme: "light" | "dark" };
type AppValue = { state: AppState; toggle: (id: number) => void };
const AppContext = createContext<AppValue | null>(null);
function useApp() {
const value = useContext(AppContext);
if (!value) throw new Error("Missing provider");
return value;
}
const SelectionCount = memo(function SelectionCount() {
const { state } = useApp();
return <Rendered label="SelectionCount">{state.selected.length} selected</Rendered>;
});
const ThemeLabel = memo(function ThemeLabel() {
const { state } = useApp();
return <Rendered label="ThemeLabel">Theme: {state.theme}</Rendered>;
});
const BookPicker = memo(function BookPicker() {
const { state, toggle } = useApp();
return (
<Rendered label="BookPicker">
{books.slice(0, 3).map((b) => (
<button key={b.id} onClick={() => toggle(b.id)}>
{state.selected.includes(b.id) ? "✓ " : ""}
{b.title}
</button>
))}
</Rendered>
);
});
export default function App() {
const [state, setState] = useState<AppState>({ selected: [], theme: "light" });
const value = useMemo(
() => ({
state,
toggle: (id: number) =>
setState((s) => ({
...s,
selected: s.selected.includes(id) ? s.selected.filter((x) => x !== id) : [...s.selected, id],
})),
}),
[state],
);
return (
<AppContext value={value}>
<SelectionCount />
<ThemeLabel />
<BookPicker />
</AppContext>
);
}ThemeLabel re-renders on every click even though the theme never changes and the component is memoized. That's not a bug in this code. It's how context works: when a provider's value changes (by Object.is), React re-renders every component that reads that context, and memo can't stop it, because the update comes from the context, not from props. There's no way for a consumer to say "I only care about state.theme".
Here three cheap components re-render. In a real app it's a list of two hundred rows, each reading a "current selection" context, all re-rendering whenever anything in that context changes, many times a second if the value is something like a cursor position or a drag state.
The usual patches help up to a point:
- Split the context into
ThemeContextandSelectionContext. Works when the split is obvious, but you end up with a provider per field, and a component reading three fields re-renders when any one changes. - Separate state from setters so components that only dispatch don't re-render. Good practice, but it doesn't help readers.
- Memoize below the consumer: have the consumer read the context and pass the slice to a memoized child. It works, and it's boilerplate at every use site.
What we actually want is for each component to subscribe to its own slice, and to re-render only when that slice changes. Context can't do that because it pushes one value to everyone. So we'll flip it: keep the state outside React, and let each component pull the part it wants.
Build it: a store is three functions#
An external store is an object with three operations:
getState()returns the current state.setState(update)replaces the state and notifies everyone.subscribe(listener)registers a callback to run on every change, and returns an unsubscribe function.
That's the whole contract. No React involved, so start without React. This runs in plain JavaScript and logs to the console.
type Listener = () => void;
function createStore<T extends object>(initial: T) {
let state = initial;
const listeners = new Set<Listener>();
return {
getState: () => state,
setState(update: Partial<T> | ((s: T) => Partial<T>)) {
const partial = typeof update === "function" ? update(state) : update;
state = { ...state, ...partial }; // always a new object: never mutate
listeners.forEach((listener) => listener());
},
subscribe(listener: Listener) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
};
}
const store = createStore({ count: 0, theme: "light" });
const unsubscribe = store.subscribe(() => console.log("changed:", store.getState()));
store.setState({ count: 1 });
store.setState((s) => ({ count: s.count + 1 }));
unsubscribe();
store.setState({ theme: "dark" }); // nobody is listening now
console.log("final:", store.getState());Two decisions in there matter later.
setState creates a new object every time and never mutates. That's what lets anyone detect a change with a cheap === comparison: if the reference is the same, nothing changed. Every library in this part depends on this, whether you write the copy yourself, Immer writes it for you (Redux Toolkit), or the library does it inside set (Zustand).
setState merges a partial, like class component setState. That's a convenience, not a requirement. Redux instead routes every change through one reducer function. Same store underneath.
Connecting it to React, the old way#
Before React 18, a "connect to an external store" hook looked like this:
function useStoreOld<T, S>(store: Store<T>, selector: (s: T) => S): S {
const [slice, setSlice] = useState(() => selector(store.getState()));
useEffect(() => {
// Subscribe after the first commit, and copy the slice into React state.
return store.subscribe(() => setSlice(selector(store.getState())));
}, [store, selector]);
return slice;
}It already has the selector idea: setSlice with an unchanged primitive bails out, so components only re-render when their slice changes. Libraries shipped hooks like this for years. It has two problems.
First, a gap between render and subscribe. The component reads the store during render, but subscribes later in an effect. If the store changes in between, the component misses that update until the next one. Libraries papered over it with a re-check inside the effect.
Second, and much worse once React became concurrent: tearing.
Tearing#
Since React 18, rendering can be interruptible. A render started inside a transition doesn't block the main thread: React renders a few components, checks whether its time slice is up, and if so yields to the browser so it can handle clicks, timers and network callbacks before continuing. That's what keeps a big transition from freezing the page, as you saw in the transitions chapter.
React's own state is safe across those pauses: an update made during the pause is queued and applied in a later render, so one render pass sees one consistent version of useState everywhere. An external store has no such protection. It's a plain variable, and anything that runs during the pause can change it. Components rendered before the pause saw the old value; components rendered after see the new one. Commit that, and the screen shows two versions of the same store at once. That's called tearing: the UI is torn between two states.
A transition starts rendering three components that read the same external store. The store holds 1. React renders A, which reads 1.
You can watch it happen. Six slow components read a plain mutable variable directly during render. The button starts a timer that bumps the variable every couple of milliseconds, then renders the six cells inside a transition, so React yields between them. The timer stops when the render commits.
import { startTransition, useEffect, useState } from "react";
import { slowDown } from "guide-tools";
// A mutable value outside React, read directly during render.
let external = 0;
let timer: ReturnType<typeof setInterval> | undefined;
function startTicking() {
clearInterval(timer);
const stopAt = Date.now() + 1000;
timer = setInterval(() => {
external += 1;
if (Date.now() > stopAt) clearInterval(timer);
}, 2);
}
function Cell() {
slowDown(30); // slow enough that React yields after each cell
return <span style={{ padding: "4px 10px", border: "1px solid #d6d3d1", borderRadius: 6 }}>{external}</span>;
}
export default function App() {
const [round, setRound] = useState(0);
useEffect(() => clearInterval(timer), [round]); // stop once the render commits
return (
<div>
<button
onClick={() => {
startTicking();
startTransition(() => setRound((r) => r + 1));
}}
>
Render in a transition
</button>
<p>Every cell reads the same variable during the same render:</p>
<div style={{ display: "flex", gap: 8 }}>
{[1, 2, 3, 4, 5, 6].map((i) => (
<Cell key={i} />
))}
</div>
</div>
);
}The cells show different numbers from one render. Now the same thing through useSyncExternalStore, the hook React added in version 18 for exactly this (you first used it in Custom hooks; here's the problem it was built to solve):
import { startTransition, useEffect, useState, useSyncExternalStore } from "react";
import { slowDown } from "guide-tools";
let external = 0;
const listeners = new Set<() => void>();
function subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
const getSnapshot = () => external;
let timer: ReturnType<typeof setInterval> | undefined;
function startTicking() {
clearInterval(timer);
const stopAt = Date.now() + 600;
timer = setInterval(() => {
external += 1;
listeners.forEach((l) => l());
if (Date.now() > stopAt) clearInterval(timer);
}, 2);
}
function Cell() {
const value = useSyncExternalStore(subscribe, getSnapshot);
slowDown(30);
return <span style={{ padding: "4px 10px", border: "1px solid #d6d3d1", borderRadius: 6 }}>{value}</span>;
}
export default function App() {
const [round, setRound] = useState(0);
useEffect(() => clearInterval(timer), [round]);
return (
<div>
<button
onClick={() => {
startTicking();
startTransition(() => setRound((r) => r + 1));
}}
>
Render in a transition
</button>
<p>Same cells, read through useSyncExternalStore:</p>
<div style={{ display: "flex", gap: 8 }}>
{[1, 2, 3, 4, 5, 6].map((i) => (
<Cell key={i} />
))}
</div>
</div>
);
}Every cell agrees, every time. Two mechanisms are at work:
- Store updates are always urgent. When a subscribed store notifies, React schedules a synchronous (blocking) re-render of the subscribers. A blocking render doesn't yield, so nothing can change the store halfway through.
- A consistency check before commit. For a non-blocking render (a transition), React calls
getSnapshotagain for each subscribed component just before applying changes to the DOM. If any value differs from what that component rendered with, React discards the work and redoes it as a blocking render. react.dev documents this directly in theuseSyncExternalStorereference.
The price is the word blocking. An external store opts out of concurrent rendering for its updates: wrapping store.setState in startTransition doesn't make the resulting render interruptible, because the update isn't React state, and a store change during a transition forces that transition to finish synchronously. You trade the ability to keep showing old UI during a slow update for a guarantee that the screen is never torn. For shared app state that's almost always the right trade, and it's why every serious React store library now uses useSyncExternalStore or has a mode that does.
Why didn't React 17 tear?Deep dive
Before concurrent rendering, every render ran start to finish in one synchronous call. Nothing else could run in the middle of it, so a mutable store couldn't change mid-render, and reading it directly was consistent by accident. Tearing became possible the moment React learned to yield. The React 18 working group published a discussion and test suite for library authors about this, and useSyncExternalStore (originally useMutableSource) was the result. A shim package, use-sync-external-store, backports it to older React versions; react-redux 9 still imports its with-selector variant.
useStore on top of useSyncExternalStore#
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?) asks for exactly what our store already has:
subscribe(callback): ourstore.subscribe. It must return an unsubscribe function, and it should be a stable function so React doesn't resubscribe on every render. Ours is created once per store, so it's stable.getSnapshot(): returns the current value. React calls it during render, after every notification, and before commit for the consistency check. It must return the same value (byObject.is) when nothing changed.getServerSnapshot(): what to use during server rendering and hydration. We'll come back to it.
So the whole hook is one line. Here it is with the reading list's selection and theme, the same three components as the context version:
import { books, Rendered } from "guide-tools";
import { createStore, useStore } from "./store";
const appStore = createStore({ selected: [] as number[], theme: "light" as "light" | "dark" });
// Actions are plain functions. No provider, no hooks needed to call them.
function toggle(id: number) {
appStore.setState((s) => ({
selected: s.selected.includes(id) ? s.selected.filter((x) => x !== id) : [...s.selected, id],
}));
}
function flipTheme() {
appStore.setState((s) => ({ theme: s.theme === "light" ? "dark" : "light" }));
}
function SelectionCount() {
const count = useStore(appStore, (s) => s.selected.length);
return <Rendered label="SelectionCount">{count} selected</Rendered>;
}
function ThemeLabel() {
const theme = useStore(appStore, (s) => s.theme);
return <Rendered label="ThemeLabel">Theme: {theme}</Rendered>;
}
function BookPicker() {
const selected = useStore(appStore, (s) => s.selected);
return (
<Rendered label="BookPicker">
{books.slice(0, 3).map((b) => (
<button key={b.id} onClick={() => toggle(b.id)}>
{selected.includes(b.id) ? "✓ " : ""}
{b.title}
</button>
))}
</Rendered>
);
}
export default function App() {
return (
<>
<SelectionCount />
<ThemeLabel />
<BookPicker />
<button onClick={flipTheme}>Flip theme</button>
</>
);
}Select a book: SelectionCount and BookPicker flash, ThemeLabel doesn't. Flip the theme: only ThemeLabel flashes. No memo anywhere, and no provider. Each component pays only for its own slice.
Three components subscribe to one store. Each one remembers the last value its selector returned (its snapshot).
Look at what the store does and doesn't know. It notifies every listener on every change; it has no idea who cares about what. The selectivity comes from getSnapshot: React runs each component's selector against the new state and compares the result with the last one using Object.is. Same value, no re-render. So the cost of an update is "run every subscribed selector once", which is cheap if selectors are cheap, plus "re-render the components whose slice changed".
Notice too that toggle and flipTheme are plain module functions. Because the store lives outside React, you can call it from anywhere: an event handler, a WebSocket callback, a test, a function that runs before React mounts. That's a real advantage over context, and also a risk you'll see in the pitfalls.
Selector stability: the trap in getSnapshot#
The rule "getSnapshot must return the same value when nothing changed" has a sharp edge. What if a component wants two fields?
const { count, theme } = useStore(appStore, (s) => ({ count: s.selected.length, theme: s.theme }));That selector builds a new object every time it runs. So every call to getSnapshot returns something that isn't Object.is-equal to the last result, React concludes the store changed, re-renders, calls getSnapshot again, gets another new object, and loops. Run it with the console open:
import { createStore, useStore } from "./store";
const appStore = createStore({ selected: [1, 2], theme: "light" });
export default function App() {
// A new object on every call: getSnapshot never returns a stable value.
const { count, theme } = useStore(appStore, (s) => ({ count: s.selected.length, theme: s.theme }));
return (
<p>
{count} selected, theme {theme}
</p>
);
}In development React first warns that the result of getSnapshot should be cached, then the re-renders hit React's limit and it throws "Maximum update depth exceeded". This exact crash is the most common one when upgrading to Zustand 5, whose hook is the one-liner above.
There are two fixes, and you should know both.
Select primitives separately. Two useStore calls, each returning a number or a string. Primitives compare by value, so they're stable. This is the simplest fix and usually the best.
Cache by equality. Remember the last result, and if the new one is equal by some definition (usually shallow equality: same keys, each value Object.is-equal), return the old reference instead of the new one. Then getSnapshot is stable whenever the fields are.
export function shallow(a: unknown, b: unknown): boolean {
if (Object.is(a, b)) return true;
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
const ka = Object.keys(a);
const kb = Object.keys(b);
if (ka.length !== kb.length) return false;
return ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && Object.is((a as any)[k], (b as any)[k]));
}
export function useStoreWithEquality<T, S>(store: Store<T>, selector: (state: T) => S, isEqual: (a: S, b: S) => boolean = Object.is): S {
const last = useRef<{ value: S } | null>(null);
const getSnapshot = () => {
const next = selector(store.getState());
if (last.current && isEqual(last.current.value, next)) return last.current.value; // reuse the old reference
last.current = { value: next };
return next;
};
return useSyncExternalStore(store.subscribe, getSnapshot);
}Now useStoreWithEquality(appStore, (s) => ({ count: s.selected.length, theme: s.theme }), shallow) returns the same object until count or theme actually changes. You'll meet this exact function under other names: Zustand's useShallow is these few lines wrapped around a selector, and react-redux's useSelector(selector, shallowEqual) passes the equality function to useSyncExternalStoreWithSelector, from the React team's use-sync-external-store/with-selector package, which does the same caching.
Selectors that derive new arraysDeep dive
Shallow equality also rescues some derived arrays: s.books.filter((b) => !b.read) is a new array, but its elements are the same objects, and shallow comparison checks each index with Object.is, so an unchanged result passes. It can't rescue s.books.map((b) => ({ ...b, label: b.title })), which creates new elements every time, and it still runs the whole computation on every store change. For those, you memoize the selector on its inputs: recompute only when s.books changes, otherwise return the cached array. That's what Reselect's createSelector does, which you'll use in the Redux Toolkit chapter. And writing a ref during render, as useStoreWithEquality does, bends the Rules of React a little; it's safe here because the cached value is a pure function of the store, which is why both Zustand and React's own with-selector shim do the same thing.
A subtler stability rule: the selector function itself can change every render (an inline arrow is a new function each time), and that's fine. React calls the current getSnapshot each render, so a selector that depends on props, like (s) => s.books.find((b) => b.id === id), always uses the current id. What must be stable is the result, not the function.
Server rendering and where the store lives#
Two production concerns you should be able to talk about.
getServerSnapshot. During server rendering there are no subscriptions and no updates, and React needs a value that's identical on the server and during hydration on the client, or hydration produces a mismatch. That's the third argument. If you omit it, rendering on the server throws. Libraries pass their initial state (Zustand passes getInitialState).
One store per request. A store created at module scope, like appStore above, is a singleton. In the browser that's fine: one user, one tab. On a server, module scope is shared by every request, so a module-level store would leak one user's state into another user's HTML. The fix is to create the store per request and hand it down through context. Note the shape: context carries the store reference (which never changes, so context never triggers re-renders), and the store carries the values (with selector subscriptions). Redux's <Provider store>, Jotai's <Provider store> and Zustand's recommended Next.js pattern all do exactly this.
Every library is this toy#
Keep this table in mind for the next three chapters. The names change; the pieces don't.
| Toy piece | Redux Toolkit + react-redux | Zustand | Jotai |
|---|---|---|---|
createStore(initial) | configureStore({ reducer }) | create(...) or createStore from zustand/vanilla | one store holding many atoms (createStore, or the default store) |
setState(partial) | dispatch(action) through a reducer | set(partial) | set(atom, value) |
subscribe(listener) | store.subscribe | api.subscribe | store.sub(atom, listener), per atom |
useStore(store, selector) | useSelector(selector) | useStore(selector) | useAtomValue(atom) (the atom is the selector) |
shallow, equality cache | shallowEqual, createSelector | useShallow | derived atoms, selectAtom |
| Context holds the store | <Provider store> | optional context per request | <Provider store> |
The interesting differences are where the update logic lives (a reducer, inline set calls, or atoms), how fine-grained subscriptions are (one big state with selectors, or many small atoms), and how much ceremony comes with it (DevTools, middleware, conventions). That's what Redux Toolkit, Zustand and atomic state are about.
Pitfalls#
Check your understanding#
Implement createStore and useStore in store.ts. The reading list in App.tsx already uses them. When it works, marking a book as read updates the unread badge, and the theme line's render count stays at 1, because it doesn't subscribe to the books.
import { useSyncExternalStore } from "react";
type Listener = () => void;
export type Store<T> = {
getState: () => T;
setState: (update: Partial<T> | ((state: T) => Partial<T>)) => void;
subscribe: (listener: Listener) => () => void;
};
export function createStore<T extends object>(initial: T): Store<T> {
// TODO: keep the state in a closure, merge partial updates into a NEW object,
// and notify every subscribed listener after each change.
throw new Error("createStore is not implemented yet");
}
export function useStore<T, S>(store: Store<T>, selector: (state: T) => S): S {
// TODO: subscribe with useSyncExternalStore and return the selected slice.
throw new Error("useStore is not implemented yet");
}Summary selects two fields as an object, and the app crashes with "Maximum update depth exceeded". Fix it so the app renders, +1 updates the count, and Change note (which changes a field Summary doesn't read) doesn't re-render Summary. You can change App.tsx, store.ts, or both.
import { useRenderCount } from "guide-tools";
import { createStore, useStore } from "./store";
const counter = createStore({ count: 0, label: "clicks", note: "" });
function Summary() {
const { count, label } = useStore(counter, (s) => ({ count: s.count, label: s.label }));
const renders = useRenderCount();
return (
<p>
Count: {count} {label} (renders: <span data-testid="summary-renders">{renders}</span>)
</p>
);
}
export default function App() {
return (
<>
<Summary />
<button onClick={() => counter.setState((s) => ({ count: s.count + 1 }))}>+1</button>
<button onClick={() => counter.setState((s) => ({ note: s.note + "x" }))}>Change note</button>
</>
);
}Using the toy store, a component subscribes like this. The store state is { books: [...4 books], filter: "" }. Then setState({ filter: "design" }) runs. Which of these components re-render?
function A() { const n = useStore(s, (st) => st.books.length); /* ... */ }
function B() { const list = useStore(s, (st) => st.books); /* ... */ }
function C() { const list = useStore(s, (st) => st.books.filter((b) => b.title.includes(st.filter))); /* ... */ }
function D() { const f = useStore(s, (st) => st.filter); /* ... */ }How does useSyncExternalStore prevent tearing when an external store changes during a transition render?
An interviewer asks: "Why do libraries like Redux and Zustand exist if React has context?" Answer in about a minute.
An interviewer asks: "What is tearing in React, and how does useSyncExternalStore prevent it?"
Interview angle
Context re-renders every consumer when its value changes, so it's a poor fit for shared state that changes often and is read in slices. An external store fixes that: state lives in a plain object with getState, setState and subscribe, and each component subscribes through useSyncExternalStore with a selector, so it only re-renders when its slice changes by Object.is. useSyncExternalStore also prevents tearing under concurrent rendering: store updates render synchronously and React re-checks snapshots before committing a transition. The catch is that snapshots must be stable, so selectors return primitives, use shallow equality, or are memoized. Redux, Zustand and Jotai are all this model.
Why does context cause unnecessary re-renders, and why doesn't React.memo help?
What is tearing, why does concurrent rendering make it possible, and how does useSyncExternalStore prevent it?
Walk me through building a minimal global store with selectors for React.
You want a store hook to accept selectors like s => ({ a: s.a, b: s.b }). How do you build that, and where does the trick stop working?
What changes when a global store is used with server rendering?
What do you give up by moving state from React into an external store?
Recap#
- Context re-renders every consumer when its value changes, and
memocan't prevent it, so it suits rarely changing values. Use it to pass a store, not fast-changing data. - An external store is three functions:
getState,setStatethat creates a new object and notifies, andsubscribethat returns an unsubscribe. useSyncExternalStore(subscribe, getSnapshot)connects it to React. A selector insidegetSnapshotmakes each component re-render only when its slice changes, compared withObject.is.- Tearing is one render showing two versions of a store, possible because concurrent renders yield.
useSyncExternalStoreprevents it with synchronous store updates and a pre-commit snapshot check, at the cost of non-blocking updates. getSnapshotmust be stable: select primitives, cache with shallow equality, or memoize selectors. On the server, create one store per request and pass it through context.- Redux, Zustand and Jotai are this toy with different update models and conventions.
Sources#
- react.dev: useSyncExternalStore
- react.dev: useContext, optimizing re-renders when passing objects and functions
- React 18 working group: Concurrent React for library maintainers and useSyncExternalStore
- Zustand: useShallow
- React Redux: Hooks, useSelector
- Facts checked November 24, 2026.