What you'll learn: By the end of this lesson you will be able to name the questions every state tool answers (where state lives, how it changes, how readers are told, how derived values are computed), describe React context, Redux, Zustand, Jotai atoms, signals and state machines in those terms, explain how a store connects to React's rendering, spot the selector mistake that makes a component re-render on every change, and choose a tool by the shape of your problem instead of by habit.
Think of four ways to keep a household's shared information. A notebook on the kitchen table: everyone looks up when anyone writes in it. A ledger where nobody erases a line, you only append entries and the balance is computed from them. A spreadsheet, where only the cells that depend on a changed cell update. A board game rulebook, where only certain moves are legal in certain phases.
Front-end state libraries are those ways, dressed in code. This lesson does not rank them. It shows what each one models, what it costs, and how to match one to a problem. It builds on Local vs Global State in the Front End, which decides whether state should be shared at all.
The running example is the one the lab uses: a cart with an item count and a checkout status (shopping, checkout, paid), driven by the same seven events in every shape.
The core idea
- Every tool answers four questions. Where does the state live? How is it changed? How are readers told? How are derived values computed? The differences between libraries are different answers to those four, not different magic.
- Most of them plug into React the same way. A store offers
subscribeand a way to read a snapshot, and React'suseSyncExternalStorehook connects a component to it. The component re-renders when the value it read is no longer equal (byObject.is) to the one before. Signals libraries instead track reads automatically, as described below. - The expensive mistakes are about readers, not writers. Who re-renders when something changes is decided by what each reader selected and how that selection is compared.
Three illustrations run through the lesson: a minimal example (one cart written in four shapes), a realistic example (a dashboard whose filters were in one context), and a failure example (a selector that returns a new object on every call).
What every store has in common
Figure 1. Different shapes, one connection to React
How to read this: the four boxes on the left are the lab's models of the ideas behind Redux, Zustand, Jotai and XState. Whatever the shape, React needs only a way to subscribe and a way to read the current snapshot.
React's reference describes useSyncExternalStore as a hook that lets you subscribe to an external store. Its subscribe function receives a callback and returns a cleanup function. Its getSnapshot function must return the same value on repeated calls while the store has not changed, and React re-renders when the returned value differs, compared by Object.is. The snapshot must be immutable: return a new one when data changes, and otherwise the cached one. The failure example depends on these two rules.
React context and reducers (built in)
Context lets a parent make a value available to any component below it. React re-renders all components that read a context when the provider receives a different value, compared with Object.is, and memo does not prevent it. A reducer with context (the pattern in the previous lesson) is a small store whose readers are the whole subtree. It needs no library and suits rarely changing values needed in many places, such as the current user or a theme. Its limit is selection: a reader cannot ask for "only the item count", so a change to any part of the value reaches every reader. See Context and Its Render Cost in React for splitting and measuring.
Redux: one store, actions, pure reducers
Redux's documentation gives three principles. The global state lives in an object tree within a single store. The only way to change it is to emit an action, an object describing what happened. Changes are specified by pure reducers that take the previous state and an action and return the next state, without mutating the old one. Redux Toolkit is described by the project as its official recommended approach for writing Redux logic, and it removes boilerplate and allows writing immutable updates with "mutating" syntax through Immer.
What you get is a log: every change is an action, so you can replay them. The lab's reducer store keeps the action list and checks that replaying it reproduces the state. What you pay is ceremony, and a reducer that is as permissive as you write it. In the lab, pay is accepted while the cart is empty, because nothing in the shape forbids it.
For reading, React-Redux's useSelector compares the previous and current selector result by strict === by default and re-renders when they differ. Returning a new object every time always forces a re-render by default; passing shallowEqual (or using a memoized selector) avoids it.
Zustand: the store is a hook
Zustand describes itself as a small, fast and scalable "bearbones" solution. You create a store with create, and the result is a hook you can call anywhere without a provider. State and the functions that change it sit in one object, and set applies a partial update on top of the existing state:
const useBear = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
}))
const bears = useBear((state) => state.bears)
This excerpt follows the example in Zustand's introduction and is not part of the lab. The component that passes a selector re-renders when the selected state changes. The lab's setter store models exactly this: update functions live in the store and set merges. Its test shows that a component selecting only add (a function that never changes) never re-renders when state changes.
The trade-off is freedom. There is no action log and no required structure, so structure is a team convention. Because there is no provider, the store is a module-level value, with the lifetime and server-rendering caveats from the previous lesson.
Atoms: small pieces and derived values
Jotai's atom creates an atom config, which is a definition. The docs say it does not hold a value: the value lives in a store. A primitive atom needs only an initial value. A derived atom has a read function, and the reads inside it are tracked, so it is re-evaluated when an atom it read changes.
In the lab, items and status are primitive atoms, and canPay and summary are derived:
const canPay = derived((get) => get(items) > 0 && get(status) === "checkout", "canPay");
const summary = derived((get) => `${get(items)} item(s), ${get(status)}`, "summary");
In the lab's model, a component that reads canPay re-renders only when canPay changes, not when items changes from 1 to 2 while canPay stays true. That is the strength of the shape: fine-grained subscriptions without writing selectors, and derived data that is cached by dependency. The cost is that state is spread over many small pieces, which can be harder to see as a whole.
Figure 2. Dependencies between atoms
How to read this: arrows mean "is read by". Changing items recomputes both derived atoms, but only a derived atom whose value actually changed tells its readers.
Signals: tracked reads
A signal holds a value and notifies consumers when it changes. Angular defines it as a wrapper around a value that notifies interested consumers when that value changes. Writable signals are changed with set or update, and computed signals are lazily evaluated and memoized. Preact's signals are objects with a .value property, and reading .value in a component subscribes it. Passing a signal directly into JSX lets the text update without re-rendering the component, because components see the signal and not its value.
The shared idea is automatic dependency tracking: you read a value, and the system notes who read it. Compared with a selector, there is nothing to write and nothing to compare. A TC39 proposal to add signals to JavaScript exists. At the time of writing it is at Stage 1, and its own FAQ advises not to rely on the stability of the available polyfill while the API evolves. The lab does not model signals; the atom model is the closest, and it differs in how reads are tracked and how React is connected.
State machines: when the legal moves matter
A finite state machine has a finite number of states, one active at a time, and events cause transitions. Statecharts add hierarchy, concurrency and communication, according to Stately's documentation. In the lab, the machine ignores pay until checkout has begun and guards begin on a non-empty cart. A machine is the right shape when which action is allowed now is the hard part: checkout steps, upload progress, a media player. It is a poor fit for a bag of independent values.
Choosing
Figure 3. Which shape fits which problem
hard part?"} -->|"rarely changing value,
read in a subtree"| C["Context"] Q -->|"which event is legal
in which state"| M["State machine"] Q -->|"audit trail, strict
conventions, big team"| R["Reducer store"] Q -->|"many small pieces with
derived values"| A["Atoms"] Q -->|"simple shared store,
little ceremony"| Z["Setter store"] Q -->|"automatic fine-grained
updates"| S["Signals"]
How to read this: it asks for the hard part of your problem, not for the most popular tool. Many apps combine two of these, for example context for the theme and a store for the cart.
| Shape | State lives in | Changed by | Readers are told | Derived values | Main cost |
|---|---|---|---|---|---|
| Context + reducer | A provider | Dispatching actions | Every reader of the context | Computed in render | No selection, whole-subtree re-renders |
| Reducer store (Redux) | One store | Actions and pure reducers | Selectors compared with === |
Selectors | Ceremony, boilerplate |
| Setter store (Zustand) | A store hook | set calls in functions |
Selectors compared with Object.is |
In selectors or in render | No enforced structure |
| Atoms (Jotai) | A store of atom values | Writing atoms | Per atom, per derived value | Derived atoms, cached | State spread over many pieces |
| Signals | Signal objects | Writing .value or set |
Tracked reads | Computed signals | A different mental model, evolving standard |
| State machine | An actor or interpreter | Events | A snapshot subscription | Context and guards | More up-front modelling |
Build it: one cart, four models
Goal. Run the same seven events through four models and see how each answers the four questions, then watch what a selector does to re-renders.
Setup. The lab is in the course's example workspace (Node 26.12.1, pnpm). It uses React with Testing Library under jsdom, a JavaScript model of the DOM and not a browser.
cd examples/frontend
pnpm install
cd labs/state-model-shapes
pnpm test # 21 tests (pure logic and jsdom bindings)
node src/demo.ts
Steps.
- Run the demo and compare it with the output below: the log has 7 entries (section 1),
canPaychanged twice and was computed five times (section 3), and the machine ignored three events (section 4). - Open
test/bindings.test.tsx. Five readers select from the same store:Items,Status,Whole,Fresh(a new object every time) andShallow(a new object compared one level deep). Afterbeginchanges onlystatus, the test expectsItemsto have rendered twice,WholeandFreshthree times, andShallowtwice.
Expected output, captured from a real run (Node 26.12.1, 2026-11-08):
State-model shapes: one cart, four models (models of the ideas, not the libraries)
events: pay, begin, add, add, begin, pay, add
=== 1. reducer store (one state tree, pure reducer, action log)
pay -> items=0 status=paid
begin -> items=0 status=checkout
add -> items=1 status=checkout
add -> items=2 status=checkout
begin -> items=2 status=checkout
pay -> items=2 status=paid
add -> items=3 status=paid
log length: 7, notifications: 7
replay of the log equals the state: true
=== 2. setter store (update functions live in the store, set merges)
pay -> items=0 status=paid
begin -> items=0 status=checkout
add -> items=1 status=checkout
add -> items=2 status=checkout
begin -> items=2 status=checkout
pay -> items=2 status=paid
add -> items=3 status=paid
notifications: 7 (every set builds a new state object)
=== 3. atoms (small pieces of state, derived values cached by dependency)
pay -> 0 item(s), paid, canPay=false
begin -> 0 item(s), checkout, canPay=false
add -> 1 item(s), checkout, canPay=true
add -> 2 item(s), checkout, canPay=true
begin -> 2 item(s), checkout, canPay=true
pay -> 2 item(s), paid, canPay=false
add -> 3 item(s), paid, canPay=false
canPay changed 2 time(s); computed 5 time(s)
summary computed 6 time(s)
=== 4. machine (named states, events allowed per state, guards)
pay -> items=0 status=shopping (ignored)
begin -> items=0 status=shopping (ignored)
add -> items=1 status=shopping (handled)
add -> items=2 status=shopping (handled)
begin -> items=2 status=checkout (handled)
pay -> items=2 status=paid (handled)
add -> items=2 status=paid (ignored)
ignored events: PAY, BEGIN, ADD; notifications: 4
Look at the first event, pay on an empty cart. The reducer and setter models accept it and end in paid with 0 items. The machine ignores it. That is the difference between a shape that can enforce rules and one that leaves them to the author.
What the lab does not show. These are models of the ideas written for the lab, not the libraries. They leave out most of the real packages' features, middleware, devtools and performance work, and nothing here says how fast any real library is or how it is implemented. Signals and React context costs are not modelled. No browser was used.
Break it. In your own copy of test/bindings.test.tsx, change the Shallow reader's equals to Object.is. Its expected count changes from 2 to 3, and the test fails: a selector that builds a new object on every call re-renders on every change unless it is compared by value. Restore it.
In practice: a dashboard whose filters lived in one context
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
An internal analytics dashboard has about fifteen widgets (illustrative). One context holds the date range, the region, the signed-in user and a "last updated" timestamp that changes every few seconds. Every change re-renders every widget, and a profile shows widgets that never use the timestamp re-rendering whenever it changes.
Starting architecture
Figure 4. Starting point: one context, fifteen readers
How to read this: the timestamp and the filters share one value, so a clock tick costs as much as a filter change.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Split into several contexts | Timestamp readers are separated from filter readers | More providers and hooks | Splits drift as the app grows |
| A small store with selectors for filters; context for user and theme | Each widget reads only what it uses | One new dependency and a convention | Selectors that return new objects |
The decision
| Field | Decision record |
|---|---|
| Context | One context value forces every widget to re-render on every change, including a timestamp few widgets use. |
| Decision | Move the filters and the timestamp into a small store hook with selectors. Keep the user and theme in context, since they rarely change. Each widget selects primitives (a string, a number) rather than objects. |
| Consequences, good | A timestamp tick re-renders only the footer. Editing the range re-renders widgets that read the range. |
| Consequences, bad | A dependency to maintain, and a rule for writing selectors that every contributor must know. |
| Revisit when | Derived values multiply (many widgets compute from several filters), when atoms may fit better, or when the team prefers a stricter action log. |
Rollout and verification
- Add the store beside the context and move one widget at a time, running its tests after each move.
- Count renders per widget for one filter change and one tick, before and after.
- Write the selector rule down: select primitives, or compare objects by value.
The 2 a.m. failure
The overnight report widget starts using a CPU core fully after a deploy. Its selector returns { from, to } as a fresh object, and the store's timestamp ticks every second (illustrative). React-Redux's documentation says that returning a new object every time always forces a re-render by default, and Zustand's guide says a selected value causes a re-render if it changed according to Object.is. The widget re-rendered on every tick although from and to never changed.
First checks: profile for components that render on every store update, then read their selectors for object or array literals. Mitigation: select from and to separately, or compare by value (shallowEqual in React-Redux, useShallow in Zustand). Follow-up: add a render-count test for hot widgets, and add the selector rule to the review checklist.
Architect's notes
- Choose by the hard part of the problem. Legal moves point to a machine, derived data to atoms, history to a reducer store.
- Decide the selection rule once. Primitives or value comparison, written in the contribution guide.
- Keep rarely changing values in context and frequently changing values in a store with selectors.
- Do not read marketing as measurement. Measure renders and long tasks in your own app.
Common mistakes
- Choosing a tool before naming the problem. "We need Redux" is not a requirement.
- Selecting objects or arrays built on the fly. They are never equal by reference.
- Treating a model as the library. The lab's models teach the ideas; they say nothing about a real package's speed or features.
Key takeaways
- Every state tool answers four questions: where state lives, how it changes, how readers are told, how derived values are computed.
- Stores connect to React through subscribe and a snapshot; a component re-renders when its snapshot changes by
Object.is. - Context has no selection. Redux gives one store, actions and pure reducers. Zustand gives a hook store with merging
set. Atoms give cached derived values. Signals track reads. Machines restrict legal events. - The common failure is a selector that returns a new object.
Practice exercises
Exercise 1 — Starter (45 min): Take five pieces of state from an app you know. For each, write the hard part of the problem (rare change, legal moves, derived data, audit trail, fine-grained updates) and the shape from Figure 3 that fits.
Exercise 2 — Intermediate (2 hours): In the lab, add a "remove item" event to all four models. Note which shape needs the most change and which shape lets you forbid removing from an empty cart.
Exercise 3 — Advanced (half day): Build a signal-like model of your own (track reads, notify only readers of changed values), bind it to React, and compare its render counts with the lab's selector readers.
Related reading
In this course:
- Local vs Global State in the Front End, whether the state should be shared at all.
- Context and Its Render Cost in React, what a context change costs its readers.
- Memoization and Controlling Re-renders in React, the cost of re-rendering and when to prevent it.
- How Hooks Work: State, Ordering and the Rules of Hooks, what
useStateand friends do under the hood.
Official documentation
- React: useSyncExternalStore, how a component subscribes to an external store.
- Redux: Three Principles and React-Redux hooks, the store, actions, reducers and selector comparison.
- Zustand: Introduction and Preventing re-renders with useShallow.
- Jotai: atom, primitive and derived atoms.
- Preact: Signals and Angular: Signals, tracked reads, computed values and JSX binding.
- TC39 Signals proposal and Stately: State machines and statecharts.