What you'll learn: By the end of this lesson you will be able to explain why a set of boolean flags allows states that make no sense and a state machine does not, describe states, events, transitions, context, guards and actions, use a parent state so that one handler covers several child states, say in what order exit, transition and entry actions run, keep side effects outside the machine so it can be tested as plain data, and decide when a machine is worth its weight.
Think of a turnstile at a station. It is either locked or unlocked, never both. A coin unlocks it, a push locks it again, and a push while it is locked does nothing. Nobody wrote an isLocked flag, an isUnlocked flag and an isBroken flag and then wondered what it means when two are true. The rules are written as a short table: in this state, this event leads to that state.
A state machine applies the same idea to a user interface. This lesson is about how to model a request or a checkout that way, what XState adds, and where the idea stops paying off. The lab builds a small statechart engine so every rule can be read and tested. It is not XState.
The core idea
- A machine is in exactly one state at a time, and events move it. An event that no rule in the current state handles is ignored. That is the whole safety property: states that were never named cannot happen.
- Statecharts add three things to plain machines: hierarchy (states inside states), guards (conditions on a transition) and actions (work done on entering, leaving or moving). Stately's documentation names hierarchy, concurrency and communication as what statecharts add to ordinary state machines.
- The machine describes; the caller acts. A pure function from (state, event) to the next state is easy to test and to draw. The side effects it asks for are performed outside it.
Three illustrations run through the lesson: a minimal example (a request that is idle, loading, succeeded or failed), a realistic example (a checkout with a payment parent state) and a failure example (a Cancel button pressed while the card is being charged).
States, not flags
The usual way to write a request in a component is three booleans: isLoading, isError, isSuccess. Three booleans have eight combinations, and only four of them mean something. The code decides which can happen, and code written event by event tends to forget to clear a flag.
Figure 1. A request as four states
How to read this: each arrow is a rule of the form "in this state, on this event, go there". A state with no arrow for an event ignores it. There is no state in which the request is both loading and failed.
The lab runs the same story through both designs: fetch, reject, fetch, resolve, reject. The boolean version forgets to clear the error flag on the second fetch, and ends with isLoading and isError both true, then isError and isSuccess both true. The machine has four leaf states and cannot reach those combinations, because there is nothing to combine.
Minimal example: the request machine
In XState a machine is created with createMachine(config), where the config names an initial state, the states, and for each state the events it handles under on, each with a target. An actor runs the machine: createActor(machine), then subscribe, start and send. These are the Stately docs' own building blocks, shown here without a run:
import { createMachine, createActor } from 'xstate';
const fetchMachine = createMachine({
id: 'fetch',
initial: 'idle',
states: {
idle: { on: { FETCH: { target: 'loading' } } },
loading: { on: { RESOLVE: { target: 'success' }, REJECT: { target: 'failure' } } },
success: { on: { FETCH: { target: 'loading' } } },
failure: { on: { FETCH: { target: 'loading' } } },
},
});
const actor = createActor(fetchMachine);
actor.subscribe((snapshot) => console.log(snapshot.value));
actor.start();
actor.send({ type: 'FETCH' });
This snippet follows the shapes in the Stately documentation and is not executed in this course's lab. The lab models the same ideas with its own small API, so that you can read the whole engine.
Transitions: what happens to an event
Stately's documentation says transitions are written with on inside a state, and that if no transition is enabled, none is taken and the state does not change. The lab follows the same rule and returns the very same state object for an ignored event, so a UI that compares states does not re-render. In the first lab trace, a second RESOLVE that arrives while the machine is already in success is marked ignored. That is how a late duplicate response stops doing harm.
A state value tells you where the machine is. For a flat machine it is a string such as loading. With parent states it is an object in XState, and the lab uses a dotted path such as payment.processing. A UI asks "am I somewhere in payment?" with a matches check (the lab's matches, and state.matches in XState).
Context, guards and actions
A machine has context: the data that is not a state, such as an attempt count or an error message. Three more ideas make a statechart useful.
- Guards. A guard is a condition checked when an event arrives. Stately says guards should be pure, synchronous functions that return true or false, and that when several transitions match an event, each is tested in order and the first whose guard is true is taken. The lab's request retries while
attempts < 3and otherwise fails, which is two ordered transitions onREJECT. - Actions. Stately describes actions as fire-and-forget effects, defined on transitions or as entry and exit actions on a state, and
assignas the action that updates context. The lab splits actions the same way:assignchanges context, andeffect("name")only records a name. - Order. When a transition leaves and enters states, the order matters. The W3C SCXML specification says to exit the states first, then run the transition's own content, then enter the states. The lab does the same. Stately's actions page does not state an order, so do not rely on one in XState without testing it.
Figure 2. One event, three steps, in this order
(inner to outer)"] X --> T["2. Transition actions
(assign, effects)"] T --> N["3. Entry actions
(outer to inner)"]
How to read this: this is the SCXML order that the lab models. In the lab's request, the exit action of loading ("clean up request") runs before the retry transition's "schedule retry", and the entry action ("start request") runs last. The trace prints exactly that.
Parent states: one handler, many children
States can contain states. Stately calls a state with children a parent (or compound) state, and requires it to name an initial child. When an event arrives, the transitions of the deepest child are checked first, and then its parents, up to the root. The lab's checkout machine has a payment parent with the children entering, processing and done. A CANCEL handler on payment covers all three, so it is written once.
Figure 3. A checkout with a payment parent state
How to read this: the arrow from the payment box to cart is the parent's CANCEL, available in every child. The text says why it is missing while processing.
Failure example: Cancel while the charge is in flight
A parent handler applies to every child unless the child takes the event first. That is usually what you want, and sometimes it is dangerous: a Cancel that closes the payment panel while the card is being charged leaves the user thinking nothing was charged. Stately's answer is a forbidden transition: a transition that is defined but has no target and no actions. The transition selection stops looking in parent states, so the parent's CANCEL is hidden. The lab's processing state forbids CANCEL, and its trace shows the machine staying in payment.processing and marking the event ignored. After DECLINED the machine is back in payment.entering, where CANCEL works again.
Effects stay outside
A machine that performs requests inside its actions is hard to test. The lab's machine never does: effect("charge card") only appends a name to the result, and the actor hands those names to a callback in order. The lab's last scenario prints them: open payment panel, charge card, show receipt. The caller maps names to real work.
XState has its own way to do this inside the library: a state can invoke an actor, for example a promise with fromPromise, with onDone and onError transitions. Stately says an invoked actor starts when its state is entered and is stopped when the state is exited, which is how a request is cancelled when the user leaves a loading state. The lab does not model invoked actors.
Figure 4. Where each piece lives
How to read this: effects answer with more events, never by editing state directly. Everything that changes the UI goes through the machine.
In React
The @xstate/react package provides React hooks; its documentation shows useActor, which returns a tuple of snapshot, send and the actor, and useSelector, which returns only a selected value and so re-renders only when that value changes. Keep the machine definition outside the component so it is created once, and render from the state value rather than from several flags. How state like this sits among local, global and server state is in Local vs Global State in the Front End.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| A state machine for a flow | Impossible states cannot be reached; the diagram is the spec | A new vocabulary, and more code than a boolean for a trivial case |
| Booleans or a small reducer | Cheap, familiar | Combinations the code must police; easy to forget a reset |
| Parent states | One handler for many children; forbidden transitions | Event bubbling must be understood to debug |
| XState library | Tested engine, visual tools, invoked actors, React hooks | Dependency and learning cost; behaviour to verify, not assume |
| A hand-written engine (the lab) | Every rule readable | Missing parallel states, history, delays and actors |
A good rule: reach for a machine when the same screen has several modes, events that are only valid in some of them, and failure paths. A single open/closed toggle does not need one.
Build it: model, run and check a statechart
Goal. Run a small statechart engine through two machines, a request and a checkout, and compare the request with three booleans.
Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no React, no DOM, and no XState.
cd examples/frontend
pnpm install
cd labs/statechart-model
pnpm test # 45 tests
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare it with the output below.
- In "three booleans", find the first row marked
meaningful: false, and count the combinations against the machine's leaf states. - In the checkout trace, find the
CANCELthat isignoredand theCANCELthat closes the payment panel, and say which state each came from. - In "reading the machines without running them", note that the lab lists reachable states and dead ends from the config alone.
Expected output, captured from a real run (Node 26.12.1, 2026-11-08; the same output on Node 26.13.1, 2026-12-01):
=== fetch machine: success on the second attempt
start -> idle effects: [] context: {"attempts":0}
FETCH -> loading effects: [start request] context: {"attempts":1}
REJECT(message="503") -> loading effects: [clean up request; schedule retry; start request] context: {"attempts":2}
RESOLVE(data="product 42") -> success effects: [clean up request] context: {"attempts":2,"data":"product 42"}
RESOLVE(data="late duplicate") -> success ignored context: {"attempts":2,"data":"product 42"}
=== fetch machine: attempts run out, then a late response arrives
start -> idle effects: [] context: {"attempts":0}
FETCH -> loading effects: [start request] context: {"attempts":1}
REJECT(message="503 (1)") -> loading effects: [clean up request; schedule retry; start request] context: {"attempts":2}
REJECT(message="503 (2)") -> loading effects: [clean up request; schedule retry; start request] context: {"attempts":3}
REJECT(message="503 (3)") -> failure effects: [clean up request] context: {"attempts":3,"error":"503 (3)"}
RESOLVE(data="too late") -> failure ignored context: {"attempts":3,"error":"503 (3)"}
RESET -> idle effects: [] context: {"attempts":3,"error":"503 (3)"}
=== three booleans: the same story (FETCH, REJECT, FETCH, RESOLVE, REJECT)
FETCH -> {"isLoading":true,"isError":false,"isSuccess":false} meaningful: true
REJECT -> {"isLoading":false,"isError":true,"isSuccess":false} meaningful: true
FETCH -> {"isLoading":true,"isError":true,"isSuccess":false} meaningful: false
RESOLVE -> {"isLoading":false,"isError":true,"isSuccess":true} meaningful: false
REJECT -> {"isLoading":false,"isError":true,"isSuccess":true} meaningful: false
combinations of three booleans: 8; meaningful: 4; fetch machine leaf states: 4
=== checkout machine: guard, parent states, a forbidden transition
start -> cart effects: [] context: {"items":0,"cardNumberValid":false}
CHECKOUT -> cart ignored context: {"items":0,"cardNumberValid":false}
ADD_ITEM -> cart effects: [] context: {"items":1,"cardNumberValid":false}
CHECKOUT -> payment.entering effects: [open payment panel] context: {"items":1,"cardNumberValid":false}
SUBMIT -> payment.entering effects: [] context: {"items":1,"cardNumberValid":false,"error":"card number is not valid"}
SET_CARD(valid=true) -> payment.entering effects: [] context: {"items":1,"cardNumberValid":true,"error":"card number is not valid"}
SUBMIT -> payment.processing effects: [charge card] context: {"items":1,"cardNumberValid":true}
CANCEL -> payment.processing ignored context: {"items":1,"cardNumberValid":true}
DECLINED(reason="card declined") -> payment.entering effects: [] context: {"items":1,"cardNumberValid":true,"error":"card declined"}
SUBMIT -> payment.processing effects: [charge card] context: {"items":1,"cardNumberValid":true}
PAID(orderId="o-1001") -> payment.done effects: [show receipt] context: {"items":1,"cardNumberValid":true,"orderId":"o-1001"}
CANCEL -> cart effects: [close payment panel] context: {"items":1,"cardNumberValid":true,"orderId":"o-1001"}
=== checkout machine: CANCEL bubbles from a child to its parent
start -> cart effects: [] context: {"items":0,"cardNumberValid":false}
ADD_ITEM -> cart effects: [] context: {"items":1,"cardNumberValid":false}
CHECKOUT -> payment.entering effects: [open payment panel] context: {"items":1,"cardNumberValid":false}
CANCEL -> cart effects: [close payment panel] context: {"items":1,"cardNumberValid":false}
SHUTDOWN -> cart effects: [] context: {"items":0,"cardNumberValid":false}
=== reading the machines without running them
fetch: leaves [failure, idle, loading, success]
fetch: reachable [failure, idle, loading, success]
fetch: dead ends []
checkout: leaves [cart, payment.done, payment.entering, payment.processing]
checkout: reachable [cart, payment.done, payment.entering, payment.processing]
checkout: dead ends []
events accepted in payment.processing: [PAID, DECLINED, SHUTDOWN]
=== actor: effects are handed to the caller, in order
state: payment.done
1. open payment panel
2. charge card
3. show receipt
What the lab does not show. It is not XState and was never compared with the xstate package. It has no parallel states, history, final states, eventless transitions, delays or invoked actors, and its transition order follows the SCXML text, which this lesson has not confirmed for XState. The ignored marker is the lab's way to show that the same state object came back.
Break it. In src/machine.ts, in transition, change for (const source of chain(leaf)) { to for (const source of chain(leaf).reverse()) {. The root and the outermost parent are now searched before the child, and three tests fail, among them the one for the forbidden CANCEL. Revert it.
In practice: the double charge on a slow network
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
A checkout panel keeps isSubmitting, isPaid and error in three useState calls and shows a Pay button and a Cancel button. On a slow connection, some users tap Pay twice, and some tap Cancel while the first charge is still running. Support sees a few orders that were charged although the user believes they cancelled (illustrative).
Starting architecture
Figure 5. Starting point: handlers check flags by hand
How to read this: each handler has to remember every other flag. A new button or a new flag changes every handler.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
Disable the button while isSubmitting |
The second tap | One more flag to keep in step | Cancel still closes the panel mid-charge |
A state machine with a parent payment state |
Double submit and mid-charge cancel by construction | A machine, its tests, a small library or engine | Team must learn event bubbling |
| Server-side idempotency key | Duplicate charges, regardless of the UI | Server work | Does not fix what the user sees |
The decision
| Field | Decision record |
|---|---|
| Context | Flag-based handlers allow a second submit and a mid-charge cancel. |
| Decision | Model the checkout as a machine with a payment parent and children entering, processing and done. processing ignores SUBMIT and forbids CANCEL. Effects (the charge, the panel) are named and performed by the caller. Add an idempotency key on the server as well. |
| Consequences, good | The two bad paths cannot happen in the UI, and a diagram documents the flow. |
| Consequences, bad | Every new event needs a rule in each state; the team learns a vocabulary. |
| Revisit when | Several independent regions are needed at once (parallel states), or flows are long enough to need generated test paths. |
Rollout and verification
- Write the transition table as tests before the UI: for each state, the events it accepts and ignores.
- Render from the state value and remove the flags.
- Log state transitions (state, event) so a support report can be replayed.
The 2 a.m. failure
A new "Apply voucher" event is added to the cart and works, but the product owner reports that it also works while the card is processing and changes the total after the charge started (illustrative). The event was added to the root handlers, so it applies in every state. First three checks: (1) list which states accept the new event with the machine's accepted-events view; (2) check whether it was added on the root or the parent instead of the state that needs it; (3) replay the logged event sequence. Mitigation: forbid it in processing, in the same way as CANCEL. Follow-up: add a table test that lists the accepted events of every state, so a new root handler shows up in review.
Architect's notes
- Name the states first. If you cannot name them, you do not yet know the behaviour.
- Ignore by default. An event with no rule is a no-op. Add rules, not exceptions.
- Put shared handlers on a parent, and forbid them where they are dangerous.
- Keep guards pure and effects outside. That is what makes the table testable.
- Check library behaviour before relying on it. Read the version's documentation, and test the order of actions you depend on.
Common mistakes
- Using a machine for a two-state toggle.
- Keeping parallel booleans next to a machine, so impossible combinations return.
- Doing requests inside guards. Guards must be pure.
- Adding a root handler that is wrong in some states.
- Mutating context directly instead of through
assign.
Key takeaways
- A machine is in one state at a time, and an event with no rule is ignored.
- Statecharts add hierarchy, guards and actions. Deepest states are checked first, and the first passing guard wins.
- Exit actions, the transition's actions, then entry actions: the SCXML order, which you should test in any library.
- A forbidden transition hides a parent's handler for one state.
- Keep effects outside the machine, or use invoked actors for them; events carry the results back.
- Use a machine for modes, guarded events and failure paths, not for a toggle.
Practice exercises
Exercise 1 — Starter (45 min): Draw the states and events of a login form (idle, submitting, error, signed in) and list the events each state ignores. Then write them as a config for the lab's createMachine.
Exercise 2 — Intermediate (2 hours): Add a voucher event to the lab's checkout that is accepted in cart and payment.entering but not in processing. Write the table test for the accepted events of every state.
Exercise 3 — Advanced (half day): The lab has no eventless transitions. Specify what an always transition would do, how you would stop a loop of them, and which two tests you would write first.
Related reading
In this course:
- Local vs Global State in the Front End, where UI state lives before it is modelled as a machine.
- State Management Libraries Compared, stores, reducers and machines side by side.
- Form State and Validation, another place where modes and guarded transitions appear.
- Optimistic Updates and Rollback, a flow with an explicit failure path.
- Cross-Tab Sync With BroadcastChannel, sending machine events between tabs.
Official documentation
- Stately: State machines and statecharts and Machines.
- Stately: States, Transitions and Parent states.
- Stately: Guards and Actions.
- Stately: Invoke and XState with React.
- W3C: State Chart XML (SCXML), the execution order of a transition.