What You'll Learn
- 1Write a transition table that makes illegal states impossible to express
- 2Separate guards, pure context updates and effects so a machine stays predictable
- 3Recognise when a flow needs hierarchical, history or parallel states instead of more flags
- 4Generate tests that walk every reachable state rather than one happy path
Asynchronous interfaces accumulate states faster than anyone writes them down. An upload begins idle, becomes preparing, starts transferring, might pause, might fail with a retryable error, might fail with a fatal one, might be cancelled halfway, and finishes after a verification round trip that can also fail. Expressed as booleans, that is five flags and roughly thirty combinations, of which four are real. Expressed as a machine, it is a table of seven rows that a reviewer can read in one screen and a test can walk exhaustively in milliseconds. The discipline of naming the states first is worth more than whichever library you eventually pick.
The table comes before the component
Define the flow as data: an initial state, a set of named states, and the events each one accepts. Transitions are pure lookup. An event that no state handles is ignored rather than thrown, which matters because a late click from an unmounted control should not crash anything.
import { useCallback, useRef, useState } from 'react';
export const uploadMachine = {
id: 'upload',
initial: 'idle',
context: { progress: 0, error: null, attempt: 0 },
states: {
idle: { on: { SELECT: 'preparing' } },
preparing: { on: { READY: 'uploading', REJECT: 'invalid' } },
invalid: { on: { SELECT: 'preparing' } },
uploading: {
on: {
PROGRESS: { target: 'uploading', actions: ['recordProgress'] },
DONE: 'verifying',
FAIL: { target: 'failed', actions: ['recordError'] },
CANCEL: 'idle',
},
},
verifying: {
on: { VERIFIED: 'done', REJECT: { target: 'failed', actions: ['recordError'] } },
},
failed: {
on: {
RETRY: { target: 'uploading', guard: 'canRetry', actions: ['countAttempt'] },
DISMISS: 'idle',
},
},
done: { on: { RESET: 'idle' } },
},
};
export function useMachine(definition, options) {
const [snapshot, setSnapshot] = useState(() => ({
value: definition.initial,
context: { ...definition.context },
}));
const optionsRef = useRef(options);
optionsRef.current = options;
const send = useCallback(
(event) => {
setSnapshot((current) => {
const type = typeof event === 'string' ? event : event.type;
const node = definition.states[current.value];
const edge = node.on ? node.on[type] : undefined;
if (!edge) return current;
const config = typeof edge === 'string' ? { target: edge } : edge;
if (config.guard && !optionsRef.current.guards[config.guard](current, event)) {
return current;
}
const context = (config.actions || []).reduce(
(acc, name) => optionsRef.current.actions[name](acc, event),
current.context
);
return { value: config.target || current.value, context };
});
},
[definition]
);
return [snapshot, send];
}
Self transitions are deliberate here. PROGRESS targets the same state so the machine stays in uploading while the context updates, which keeps the render branch stable and avoids re-running entry effects on every tick. The reduce over actions returns a new context and nothing else: no fetches, no notifications, no timers. Effects belong outside the transition, in an effect keyed on the state you entered.
Guards decide, actions compute, effects perform
Three roles get blurred in component code and it is the source of most machine-shaped bugs. A guard answers whether a transition is allowed using only the current snapshot, and it must be free of side effects because it may be evaluated speculatively or twice. An action computes the next context, again purely. An effect does the real-world work â starting an upload, opening a socket, focusing a field â and is triggered by observing that the state changed.
Keeping them apart buys three things. Guards become table cells a product manager can review, such as retry allowed only while the attempt count is below three. Actions become unit tests that need no rendering. And effects become ordinary React effects with cleanup, so cancelling an upload is a matter of the state leaving uploading rather than a tangle of boolean checks.
import { useEffect } from 'react';
export function UploadPanel({ file, onUploaded }) {
const [snapshot, send] = useMachine(uploadMachine, {
guards: {
canRetry: (state) => state.context.attempt < 3,
},
actions: {
recordProgress: (context, event) => ({ ...context, progress: event.progress }),
recordError: (context, event) => ({ ...context, error: event.message }),
countAttempt: (context) => ({ ...context, attempt: context.attempt + 1 }),
},
});
useEffect(() => {
if (snapshot.value !== 'uploading') return undefined;
const controller = startUpload(file, {
onProgress: (progress) => send({ type: 'PROGRESS', progress }),
onDone: () => send('DONE'),
onError: (message) => send({ type: 'FAIL', message }),
});
return () => controller.cancel();
}, [snapshot.value, file, send]);
useEffect(() => {
if (snapshot.value !== 'done') return undefined;
onUploaded();
}, [snapshot.value, onUploaded]);
return (
<section aria-busy={snapshot.value === 'uploading'}>
<p>Status: {snapshot.value}</p>
{snapshot.value === 'failed' && (
<div role="alert">
<p>{snapshot.context.error}</p>
<button type="button" onClick={() => send('RETRY')}>Retry</button>
<button type="button" onClick={() => send('DISMISS')}>Dismiss</button>
</div>
)}
<progress value={snapshot.context.progress} max="100" />
</section>
);
}
The cleanup in the first effect is the payoff. When the state leaves uploading â because the user cancelled, because the request failed, because the component unmounted â the effect cleans up and the transfer stops. There is no separate cancelled flag to reconcile and no request whose late response can arrive into a state that no longer expects it.
What the component stops owning
Render the snapshot rather than coordinating it. The component above has no local boolean for whether an error should show while a request is running, no disabled attribute derived from three conditions, and no branch that asks whether a retry is allowed â the machine already answered that question before render began. What remains is mapping each state to markup, which is code a reviewer can verify by reading the table next to it.
That separation also shrinks the test surface. Component tests become a handful of assertions that a given state renders the expected controls, while the interesting behaviour â retries, cancellation, invalid ordering of events â is covered by tests that never render anything. Teams that adopt this usually find their UI test suite gets shorter and their bug reports get more specific, because a failure names the state and event rather than describing a sequence of clicks that produced the wrong pixels.
Tracing a flow you cannot reproduce
Production failures rarely arrive with steps to reproduce, and a machine gives you something better than guessing: a log of every transition with the event that caused it. Recording the previous state, the event, the next state and a timestamp turns a bug report into a handful of lines that show exactly where the flow diverged, and it is cheap enough to keep on in production behind a sampling flag.
Visualisation is the second half of the same idea. Because the transition table is data, a diagram can be generated from it, which makes the flow reviewable by people who will never open the codebase. When an engineer and a product manager look at the same graph and disagree about an edge, that conversation happens before implementation instead of after a release, and it tends to be the conversation that would otherwise have surfaced as a support ticket three weeks later.
When one level of states is not enough
Flat machines cover most screens. The cracks appear when a state has a subflow of its own, when the user leaves and should return to where they were, or when two independent things happen at once. A statechart adds exactly those three constructs, and each one trades a little simplicity for a large reduction in duplicated transitions.
| Kind | Models | Example | What it costs |
|---|---|---|---|
| Flat | A simple sequence | idle to loading to done | Nothing |
| Hierarchical | A subflow inside a state | uploading with connecting, transferring, finalising | Entry and exit rules per level |
| History | Returning to a previous substate | Drawer reopens on the tab it closed with | One history pointer to initialise |
| Parallel | Independent regions at once | Player streaming while captions toggle | Regions multiply the combinations |
Hierarchical states pay off when every outer event would otherwise have to be listed in each inner state. Cancel during connecting, cancel during transferring and cancel during finalising are one transition on the parent, not three copies that drift apart. History states pay off in navigation-heavy overlays where the alternative is threading the previous tab through component state. Parallel regions are the most expensive and the most clarifying: a call interface with an independent media region and a chat region is two small machines running side by side rather than one machine whose state names read like sentences.
Testing the whole graph instead of one path
Because transitions are data, a test can enumerate them. Start from the initial state, apply every event from the definition, record which states become reachable, and repeat until the set stops growing. The result tells you two useful things before you write a single assertion: unreachable states are dead code worth deleting, and states with no outgoing events are traps the user cannot escape.
import { uploadMachine } from './uploadMachine';
export function reachableStates(machine) {
const seen = new Set([machine.initial]);
const queue = [machine.initial];
while (queue.length) {
const current = queue.shift();
const node = machine.states[current];
const events = Object.keys(node.on || {});
events.forEach((event) => {
const edge = node.on[event];
const target = typeof edge === 'string' ? edge : edge.target;
if (target && !seen.has(target)) {
seen.add(target);
queue.push(target);
}
});
}
return [...seen];
}
describe('upload machine', () => {
it('makes every declared state reachable', () => {
expect(reachableStates(uploadMachine).sort()).toEqual(
Object.keys(uploadMachine.states).sort()
);
});
it('blocks retry once the attempt limit is reached', () => {
const fullContext = { progress: 0, error: 'boom', attempt: 3 };
expect(guards.canRetry({ context: fullContext })).toBe(false);
});
});
Pair that with a path walk that sends each sequence of events through the real interpreter and asserts the terminal state, and the coverage problem largely disappears. These tests run without rendering, without a network mock and without timers, so they belong in the fastest suite you own.
Choosing between a machine, a reducer and a library
Two independent booleans that never interact do not need a machine, and neither does a component whose only states are loading and loaded. The threshold is disagreement: when a second piece of state must agree with the first, when you find a comment saying a combination should be impossible, or when a flow now has a retry path that must return somewhere specific.
Write the table first regardless of the eventual implementation. It is the artefact that survives a rewrite, the thing a product manager can correct, and the seed of the test suite. If the flow stays small, the fifty-line interpreter above is enough. When you find yourself wanting nested states, invoked promises, visualisation or typed events, move the same table into a library such as XState rather than extending an interpreter you no longer enjoy maintaining.
Common Mistakes
Running fetches and timers inside transition actions so the machine is no longer pure
Fix: Update context in actions and perform effects from an effect keyed on the entered state
Encoding one state with four booleans and defending against impossible combinations in render
Fix: Name the states and let the transition table make the impossible ones unrepresentable
Adding a new state without checking whether anything can leave it
Fix: Run a reachability walk and look for states with no outgoing transitions
Letting a late response arrive after the user cancelled
Fix: Clean up the effect when the state exits so the request dies with the state
Best Practices
- Write the transition table as a reviewable artefact before writing component code
- Keep guards pure and free of side effects so they can be evaluated speculatively
- Treat the machine as the single source of truth and derive rendering from its snapshot
- Enumerate reachable states in tests and delete anything unreachable
- Stay with plain state until a second boolean must agree with the first
Key Takeaways
- A machine makes illegal states unrepresentable instead of defending against them at render time
- Guards decide, actions compute context, effects perform work â blurring them breaks predictability
- Hierarchical, history and parallel states each remove a specific kind of duplicated transition
- Transition tables are data, so reachability and path tests generate themselves
- The table is the durable artefact; the interpreter underneath it can always be swapped