Skip to content

Lesson 28 of 37React at scale

State Management at Scale

Classify state before picking a tool, learn how stores plug into React through useSyncExternalStore, and choose between Zustand, Redux Toolkit and Jotai.

16 min read0/4 questions

You can now set up, type, style and test a React project. This unit is about what changes when that project and its team grow. Say you join a team whose Redux store has grown to a few thousand lines. Most of it is API responses copied into slices, each with its own isLoading, error and lastFetched fields, and a thunk per endpoint to fill them. Bugs show up as stale lists after a save, the same request fired twice from two screens, and filters that reset when you press Back. None of that is really a Redux problem. It is a classification problem: different kinds of state were all put in one place. This lesson teaches you to sort state into its kinds first, then shows how stores actually connect to React and when Zustand, Redux Toolkit or Jotai is the right pick.

Classify before you choose

In Context you saw a short comparison of stores, and the React architecture lesson gave you a ladder for where state should live. At scale the more useful question is what kind of state you are holding, because each kind has an owner that already solves its hard parts.

KindExamplesHard partsOwner
Server cacheOrders, the current user's profile, search resultsCaching, refetching, deduplication, invalidation after writesTanStack Query, RTK Query, or the framework (Server Components, loaders)
URL stateFilters, sort, page number, selected tab, open item idShareable links, Back and Forward, refreshThe router (useSearchParams, nuqs)
Form stateField values, touched, errors while editingValidation, dirty tracking, submitA form library or React 19 Actions
Local UI stateA dropdown is open, hover, a draft commentNothing, keep it localuseState, useReducer
Global client stateA multi-step editor document, a cart before checkout, a draggable layout, the audio playerMany readers, frequent writes, no server copyA store: Zustand, Redux Toolkit, Jotai

Run the team's store through this table and most of it disappears. The API data moves to a server cache, the filters move to the URL, and what is left (maybe the editor and some UI preferences) is a small store that is easy to reason about.

Where does this piece of state belong?
Comes from the server?Comes from the server?Server cache: TanStack Query, RTK QueryServer cacheTanStack Query, RTK QueryShould a link restore it?Should a link restore it?URL: search paramsURLsearch paramsUsed by one subtree?Used by one subtree?Local or lifted: useState, useReducerLocal or lifteduseState, useReducerClient store: Zustand, Redux, JotaiClient storeZustand, Redux, Jotaiyesnoyesnoyesno, shared widely

Ask first whether the server is the source of truth. If it is, your copy is a cache, and caches need invalidation, not reducers.

1/5
Match the pairs0/5 matched

Match each piece of state to the kind it is.

Choose an item, then its match on the other side.

URL state and derived state

Teams underuse the URL. If a filter lives in useState, a refresh loses it, a link to a colleague shows them something else, and the Back button jumps past it. If it lives in the search params, all three work, and the router becomes your state container.

OrdersPage.tsx
const STATUSES = ["all", "pending", "shipped"] as const;
type Status = (typeof STATUSES)[number];
 
function useStatusFilter() {
  const [params, setParams] = useSearchParams(); // from your router
  const raw = params.get("status");
  const status: Status = STATUSES.includes(raw as Status) ? (raw as Status) : "all"; // never trust the URL
 
  function setStatus(next: Status) {
    setParams((p) => {
      p.set("status", next);
      p.delete("page"); // a new filter starts at page 1
      return p;
    }, { replace: true });
  }
  return [status, setStatus] as const;
}

Three habits matter. Validate what you read, because anyone can type any URL. Choose push or replace on purpose: a new filter on every keystroke should replace the history entry, while opening an item should push, so Back closes it. And for many typed params, a small library like nuqs parses, validates and serializes them for you.

The other half is derived state. Once the filter is in the URL, do not copy it into useState "for convenience", and do not store filteredOrders anywhere. Compute it during render from the cache and the URL. Every copy of the same fact is a chance for the copies to disagree, and the classic sign is an effect whose only job is to keep two pieces of state in sync, the pattern useEffect warned you about.

How a store plugs into React

A store keeps state outside React, in a plain module. React needs two things from it: a way to read the current value, and a way to hear about changes. useSyncExternalStore is the hook that connects them, and Zustand, Redux (through react-redux) and many others are built on it.

const value = useSyncExternalStore(subscribe, getSnapshot);
  • subscribe(callback) registers a listener and returns an unsubscribe function.
  • getSnapshot() returns the current value. React calls it during render and after every notification, compares the result with the previous one using Object.is, and re-renders only if it changed.

That comparison is the whole performance story of stores. A component that selects state.count re-renders when the count changes and not when anything else does. Here is the same logic without React, so you can watch it work.

TypeScriptselectors.ts
type Listener = () => void; function createStore<T extends object>(initial: T) { let state = initial; const listeners = new Set<Listener>(); return { getState: () => state, setState(partial: Partial<T>) { state = { ...state, ...partial }; // a new object, never a mutation listeners.forEach((l) => l()); }, subscribe(l: Listener) { listeners.add(l); return () => listeners.delete(l); }, };} // What a selector hook does on every store changefunction watch<T extends object, S>(store: ReturnType<typeof createStore<T>>, name: string, selector: (s: T) => S) { let last = selector(store.getState()); store.subscribe(() => { const next = selector(store.getState()); if (!Object.is(last, next)) { console.log(`${name} re-renders`); last = next; } });} const store = createStore({ count: 0, user: { name: "Ada" }, theme: "light" });watch(store, "Counter", (s) => s.count);watch(store, "Avatar", (s) => s.user); console.log("-- increment");store.setState({ count: 1 });console.log("-- toggle theme");store.setState({ theme: "dark" });console.log("-- rename");store.setState({ user: { name: "Grace" } });
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

Using the store above, a third component selects an object. What is printed after these two updates?

watch(store, "Header", (s) => ({ name: s.user.name, theme: s.theme }));

console.log("-- increment");
store.setState({ count: 2 });
console.log("-- same theme");
store.setState({ theme: "dark" });
Need a nudge? Hints walk you through it.

Now the real thing. The store below is about fifteen lines, and the hook is one call to useSyncExternalStore. Click the buttons and watch the console: each component renders only when its own slice changes.

ReactTinyStore.tsx
import { useSyncExternalStore } from "react"; type State = { count: number; name: string };let state: State = { count: 0, name: "Ada" };const listeners = new Set<() => void>(); const store = { getState: () => state, setState(partial: Partial<State>) { state = { ...state, ...partial }; listeners.forEach((l) => l()); }, subscribe(l: () => void) { listeners.add(l); return () => listeners.delete(l); },}; function useStore<S>(selector: (s: State) => S): S { return useSyncExternalStore(store.subscribe, () => selector(store.getState()));} function Count() { const count = useStore((s) => s.count); console.log("render Count"); return <p>Count: {count}</p>;} function Name() { const name = useStore((s) => s.name); console.log("render Name"); return <p>Name: {name}</p>;} export default function App() { return ( <div> <Count /> <Name /> <button onClick={() => store.setState({ count: store.getState().count + 1 })}>Increment</button>{" "} <button onClick={() => store.setState({ name: store.getState().name === "Ada" ? "Grace" : "Ada" })}>Rename</button> </div> );}

Notice App never re-renders. The buttons write to the store directly, and only the subscribed components update. Compare that with Context, where changing the provider value re-renders every consumer.

Tearing, and why the hook exists

Why not subscribe in a useEffect and copy the value into useState, as people did before? Concurrent rendering. During a transition React can pause halfway through rendering a tree, let the browser handle input, and continue. If an external store changes during that pause, components rendered before the pause saw the old value and components after it see the new one. The screen shows two different versions of the truth at once. That is called tearing.

useSyncExternalStore prevents it. React checks the snapshot again before committing, and if it changed, it throws away the inconsistent work and re-renders synchronously. The trade-off is one seniors know: updates that come from an external store are always treated as blocking. You cannot mark a store update as a transition and have React keep showing the old UI while the new one renders. If you need that, keep that piece of state in React (useState or useReducer with startTransition).

A store update reaching one component
ClickStoreReactCountsetState({ count: 1 })notify listenersgetSnapshot()1 (was 0)re-render

The handler writes to the store. React is not involved yet.

1/5

Zustand

Zustand is the most common choice for new React apps that need a client store. It is small, needs no provider, and is this exact pattern with good defaults.

stores/editor.ts
import { create } from "zustand";
import { persist } from "zustand/middleware";
 
type Shape = { id: string; x: number; y: number };
type EditorState = {
  shapes: Shape[];
  selectedId: string | null;
  select: (id: string | null) => void;
  move: (id: string, x: number, y: number) => void;
};
 
export const useEditor = create<EditorState>()(
  persist(
    (set) => ({
      shapes: [],
      selectedId: null,
      select: (id) => set({ selectedId: id }),
      move: (id, x, y) =>
        set((s) => ({ shapes: s.shapes.map((sh) => (sh.id === id ? { ...sh, x, y } : sh)) })),
    }),
    { name: "editor", partialize: (s) => ({ shapes: s.shapes }) }, // persist the doc, not the selection
  ),
);
Toolbar.tsx
import { useShallow } from "zustand/react/shallow";
 
const selectedId = useEditor((s) => s.selectedId); // re-renders only when selection changes
const move = useEditor((s) => s.move); // actions never change, so this never re-renders
const { shapes, select } = useEditor(useShallow((s) => ({ shapes: s.shapes, select: s.select })));

The habits that keep a Zustand codebase fast:

  • Always pass a selector. useEditor() with no selector subscribes to the whole store, and the component re-renders on every change.
  • Select primitives, or wrap object selectors in useShallow. Since Zustand v5, a selector that returns a new object or array each time can cause an infinite loop, for the reason the Predict above showed.
  • Keep actions in the store. Components call move(...) instead of building new state themselves, which keeps update logic in one testable place.
  • Split big stores into slices: one function per feature that returns its part of the state and actions, combined in one create. Or use separate stores per feature.
  • Use persist with partialize, and add version and migrate once you have shipped, because the shape stored in a user's browser outlives your deploys.
Quick check
After upgrading to Zustand v5, const { count, inc } = useCounter((s) => ({ count: s.count, inc: s.inc })) crashes with a maximum update depth error. What is the fix?
Need a nudge? A hint rules out a wrong answer.

Redux Toolkit

Redux Toolkit (RTK) is the modern, official way to write Redux. It removes most of the boilerplate that gave Redux its reputation: createSlice generates action creators from your reducers, and Immer lets you write updates that look like mutations while producing new objects.

store/cart.ts
import { configureStore, createSelector, createSlice, type PayloadAction } from "@reduxjs/toolkit";
 
type Line = { id: string; qty: number; price: number };
 
const cart = createSlice({
  name: "cart",
  initialState: { lines: [] as Line[] },
  reducers: {
    added(state, action: PayloadAction<Line>) {
      state.lines.push(action.payload); // Immer turns this into an immutable update
    },
    removed(state, action: PayloadAction<string>) {
      state.lines = state.lines.filter((l) => l.id !== action.payload);
    },
  },
});
 
export const { added, removed } = cart.actions;
export const makeStore = () => configureStore({ reducer: { cart: cart.reducer } });
export type RootState = ReturnType<ReturnType<typeof makeStore>["getState"]>;
 
export const selectTotal = createSelector(
  [(s: RootState) => s.cart.lines],
  (lines) => lines.reduce((sum, l) => sum + l.qty * l.price, 0), // recomputed only when lines change
);

It is the same reducer and action model you learned in useReducer, made global. RTK Query, included in the package, is a server cache in the same style: you declare endpoints with createApi, get generated hooks like useGetOrdersQuery, and tag-based invalidation refetches lists after a mutation. Teams already on Redux should use it instead of hand-written thunks that copy responses into slices.

Large teams still pick Redux on purpose. Every change is an action with a name, so the Redux DevTools show a complete, replayable history, which is valuable when many people work on one complicated client. The conventions are strict and well documented, so a new hire knows where things go. Middleware such as the listener middleware gives one place for cross-cutting side effects. The cost is more ceremony than Zustand for small apps.

Jotai

Jotai turns the model around. Instead of one store you read from, you declare many small atoms and derived atoms, and components subscribe to exactly the atoms they use.

import { atom, useAtom, useAtomValue } from "jotai";
 
const widthAtom = atom(800);
const heightAtom = atom(600);
const areaAtom = atom((get) => get(widthAtom) * get(heightAtom)); // derived, recalculated on demand
 
function AreaLabel() {
  const area = useAtomValue(areaAtom); // re-renders only when width or height change
  return <span>{area}px²</span>;
}

It shines when state is a web of many independent, interdependent values, such as a design tool's properties panel or a spreadsheet-like form, where writing selectors for each would be tedious. For a few related values with clear actions, Zustand is simpler.

Testing stores

Stores are plain code, so test most of the logic without rendering anything: call actions, then assert on getState(). Two rules prevent flaky suites.

  • Reset between tests. Module-level stores keep state across tests in the same file. With Zustand, reset in afterEach with useEditor.setState(useEditor.getInitialState(), true) (the true replaces instead of merging), or follow the Zustand docs' mock that resets every store automatically.
  • Build a fresh store per test where the library allows it. This is why the RTK example exports makeStore instead of a single store: each test, and each server request, gets its own, optionally with preloadedState for the scenario.
cart.test.ts
test("removing a line updates the total", () => {
  const store = makeStore();
  store.dispatch(added({ id: "a", qty: 2, price: 5 }));
  store.dispatch(added({ id: "b", qty: 1, price: 3 }));
  store.dispatch(removed("a"));
  expect(selectTotal(store.getState())).toBe(3);
});

For components, render them with a real store (fresh per test) rather than mocking the hook, so the test checks what the user sees.

Choosing a store

SituationReasonable choice
Mostly API data, a few UI flagsNo store: a server cache plus local state and the URL
A small amount of shared client stateZustand, or Context if it rarely changes
A large client with many contributors, needing an audit trail of changesRedux Toolkit with RTK Query
Many fine-grained interdependent valuesJotai
Values read everywhere but changed rarely: theme, localeContext
Quick check
Which statement about useSyncExternalStore is true?
Need a nudge? A hint rules out a wrong answer.
Key terms
server cache
A client-side copy of data owned by the server. It needs caching, refetching and invalidation, not reducers.
URL state
State kept in the path or search params, so links, refresh and the Back button restore it.
derived state
A value computed during render from other state. Storing a copy of it invites the two to disagree.
useSyncExternalStore
The React hook that subscribes a component to a store outside React and reads a snapshot, re-rendering only when the snapshot changes.
selector
A function that picks the part of store state a component needs, so it re-renders only when that part changes.
tearing
Different components showing different values of the same store in one render, possible when a store changes during a concurrent render.
atom
Jotai's unit of state. Derived atoms compute from other atoms, and components subscribe to individual atoms.