What you'll learn: By the end of this lesson you will be able to describe a screen as a finite set of states, events and transition rules, write the rules as a table, explain why an event with no rule is simply ignored, type a table in TypeScript so that a missing state or a misspelled target does not compile, derive which buttons are enabled from the table itself, keep effects outside the machine and answer them with events, refuse a late response from a cancelled request with a guard, read a table without running it, generate test paths from it, and say what a library such as XState adds that a small flat machine does not.
Think of a vending machine. It is waiting, or it has coins in it, or it is dispensing. Pressing the product button while it is waiting does nothing, and nobody wrote a rule saying "ignore the button when there is no money": the machine only has rules for what it can do in each situation. Many front-end bugs of the "how did it get into that state" kind come from code built the other way round, with independent switches and handlers that each have to remember all the others.
A finite state machine (FSM) is the vending machine written down. This lesson is the plain, flat version: no nesting, no parallel regions. State Machines With XState covers statechart ideas and the library; Statecharts and Hierarchical State, a later lesson, goes further. Here the focus is the table itself: how to write, type, test and read it.
Three illustrations run through the lesson: a minimal example (a save button), a realistic example (a file upload with pause and retry) and a failure example (an answer from a request the user already cancelled). The lab models all three with a typed engine of about 250 lines. It is not XState; a section below lists what the library does that the lab does not.
The core idea
- A machine has a finite set of states and is in exactly one of them. Stately's documentation says a state machine can only be in one state at a time, and that the set of states is finite.
- Events cause transitions, and the same state and event always lead to the same next state. The documentation calls the transitions deterministic. Context (data that is not a state, such as a retry count) and guards (conditions) refine a rule without changing that shape.
- What the machine does not name cannot happen. An event with no rule in the current state changes nothing. The design effort moves from "what could go wrong" to "what is each state for".
The machine as a table
A flat machine is four things: a set of states, a set of event types, an initial state and a transition function from (state, event) to the next state. In code that function is a table with one row per state.
| State | EDIT |
SAVE |
SAVED |
FAILED |
|---|---|---|---|---|
clean |
to dirty |
ignored | ignored | ignored |
dirty |
ignored | to saving (send request) |
ignored | ignored |
saving |
stay, remember the edit | ignored | to clean, or to dirty if an edit happened |
to error |
error |
to dirty |
to saving (send request) |
ignored | ignored |
Every blank cell is a decision: "this event is meaningless here". Two cells carry the interesting behaviour. SAVE while saving is ignored, which is what stops a double click from sending two requests. SAVED has two rules, tried in order, because an edit made while the request was in flight means the saved copy is already out of date.
Figure 1. A save button
How to read this: each arrow is one rule, "in this state, on this event, go there". A state with no arrow for an event ignores it. The two arrows out of saving on success are the two ordered rules for SAVED.
Illustration 1: the minimal example
The lab's saveButton is this table as data. The trace below sends EDIT, SAVE, EDIT, SAVED, SAVE, SAVE, FAILED and shows the state after each event, the word ignored when no rule applied, and the effects the machine asked for.
Expected output, captured from a real run (Node 26.13.1, node src/demo.ts in examples/frontend/labs/fsm-ui):
=== 1. save button: an edit while saving sends the button back to dirty
EDIT -> dirty
SAVE -> saving effects: [send save request]
EDIT -> saving
SAVED -> dirty
SAVE -> saving effects: [send save request]
SAVE -> saving ignored
FAILED{"message":"offline"} -> error effects: [show error]
The edit during the first save does not change the state, but it is remembered, so SAVED lands in dirty. The second SAVE while saving is ignored, so only one request was named. Nothing checks "am I already saving"; the table has no cell for it.
Counting states
Suppose the upload in the next section used four booleans: uploading, paused, failed, done. Four booleans take 2 to the power 4, which is 16, values. The lab's reading is that at most one flag should be true, which leaves 5 meaningful values, and the machine has exactly 5 states. The other 11 are "impossible states" that flag code must avoid by hand, in every handler.
The lab reproduces how they arrive. Flag-style handlers set what each event is about and forget the rest: after START, FAIL, RETRY and DONE the flags say uploading, failed and done at once. A careful team would clear the flags, but that is the point: with flags every handler must clear every other flag, while a machine's state is one value, so there is nothing to forget. Stately's documentation makes the same argument: a finite, explicit set of states makes invalid combinations easy to spot.
Ignored events are a feature
When no rule matches, the lab's step returns the same snapshot object it was given, plus handled: false. Two consequences follow.
- Late and duplicate events are harmless by default. A second
DONE, a click on a button that should be off, a response after the user left: none can corrupt a state that has no rule for them. - Identity can skip work. React's documentation says that if a reducer returns the state identical to the current one under
Object.is, React skips re-rendering the component and its children. Astepused as a reducer therefore costs no render for an ignored event. (The lab has no React; this is a property of the shape, not something it measured.) The same page says a reducer must be pure and that Strict Mode calls it twice to expose impurities;stepis pure for that reason.
The risk is the mirror image: a rule you forgot is also ignored, silently. The section on reading the table shows how to list every ignored pair for review.
Writing the table in TypeScript
A table is easy to get subtly wrong: a state with no row, a target that is a typo, an event type that no longer exists. TypeScript can reject all three. The lab's type is short enough to read whole:
export type Table<S extends string, E extends AnyEvent, C> = {
readonly [K in S]: { readonly [T in E["type"]]?: Handler<S, C, E, T> };
};
S is the union of state names and E the union of event objects, each with a type field. The mapped type [K in S] is not optional: the table needs a row for every state, so adding a state to the union breaks every machine that lacks its row. Inside a row, [T in E["type"]]? allows only event types of the union, and each rule's guard and update receive the event narrowed to that type with Extract. The target to has type S.
This is the idea of exhaustiveness checking in the TypeScript handbook: narrowing a union to nothing leaves never, and assigning to never in a default branch makes the compiler report any member you forgot. The lab's tests keep four @ts-expect-error lines (a missing row, an unknown target, an unknown event type, a guard reading a field the event lacks); the type check fails if any of them stops being an error. defineMachine repeats the first two checks at run time, for tables loaded from JSON or written in plain JavaScript.
The screen uses the same trick: the view is a Record<UploadState, ...>, so a new state without something to show does not compile.
Effects stay outside, events come back
A machine that makes the request inside its rules cannot be tested without a server. The lab's rules only name effects ("start upload", "abort upload") in a list. The caller performs them and sends the outcome back as an event.
Figure 2. Who does what
How to read this: the machine never reaches the network, and the network never edits state. A timeout is an event sent by a timer the caller owns. In XState, a delayed transition (after) puts the timer in the machine, and the documentation says the timer is cancelled when the state is exited; in the lab, the caller owns and cancels it.
The realistic example: an upload
A seller dashboard uploads a product photo. The screen has five states, nine event types, a size limit and a retry limit (both illustrative values chosen for the lab: 5,000,000 bytes and 3 attempts). The context holds the request id, the file name, the progress, the attempt count and the last error.
Figure 3. The upload machine
How to read this: progress events keep the machine in uploading and only change the context, so they are not drawn. RETRY has a guard, which is why it is labelled with a condition.
Expected output, captured from a real run (the second and third scenarios of the same demo):
=== 2. upload: pause, resume, finish; then a file that is too large
SELECT{"name":"photo.jpg","bytes":1200000} -> uploading effects: [start upload]
PROGRESS{"req":1,"percent":40} -> uploading
PAUSE -> paused effects: [pause upload]
DONE{"req":1} -> paused ignored
RESUME -> uploading effects: [resume upload]
DONE{"req":1} -> done effects: [show receipt]
RESET -> idle
SELECT{"name":"video.mp4","bytes":9000000} -> idle
=== 3. upload: retries run out
SELECT{"name":"a.png","bytes":10} -> uploading effects: [start upload]
FAIL{"req":1,"message":"503"} -> failed effects: [show error]
RETRY -> uploading effects: [start upload]
FAIL{"req":2,"message":"503"} -> failed effects: [show error]
RETRY -> uploading effects: [start upload]
FAIL{"req":3,"message":"503"} -> failed effects: [show error]
RETRY -> failed ignored
buttons enabled in "failed": [Cancel]
Three things to see. The oversized file stays in idle and only the context records the error. The third RETRY is ignored because its guard, attempts below the limit, now fails. And the last line shows the payoff: the screen did not need a separate rule for "disable Retry after three failures". Each state has a list of buttons, and enabledButtons keeps those the machine would accept right now, guards included. The interface and the rules cannot disagree, because the interface is read from the rules.
A DONE that arrives while the upload is paused is also ignored in the first trace. That is a design decision hidden in a blank cell. It is deliberate in the lab, and it comes back as the 2 a.m. failure below.
The failure example: an answer from a cancelled request
Every SELECT and every RETRY starts a request and raises the request id in the context by one. The caller echoes the id in PROGRESS, FAIL and DONE, and a guard accepts them only when the id equals the one in the context. Without the guard, here is what happens: the user selects a.png (request 1), cancels, selects b.png (request 2), and then the answer to request 1 arrives. The machine is in uploading again, so DONE matches the rule.
Figure 4. Request 1 answers after request 2 started
How to read this: aborting a request does not guarantee that its answer never arrives, since it may already be on its way. The id in the event is what lets the machine tell the old answer from the new.
Expected output, captured from a real run (the fourth scenario; the machine is built twice, once without the check):
=== 4. stale response: cancel, pick another file, then the first request answers
guardStale=false
SELECT{"name":"b.png","bytes":10} -> uploading effects: [start upload]
DONE{"req":1} -> done effects: [show receipt]
final: state=done file=b.png percent=100
guardStale=true
SELECT{"name":"b.png","bytes":10} -> uploading effects: [start upload]
DONE{"req":1} -> uploading ignored
final: state=uploading file=b.png percent=0
Without the check, the machine is done with file=b.png and percent=100 although request 2 never finished: the screen shows a success for a photo that was not uploaded. With the check the stale event is ignored, and the same table-driven rule (no match, nothing happens) does the work. Cancelling the request with an AbortSignal and checking the id are complementary; Request Cancellation, Retries and Timeouts covers the first.
Reading the table without running it
Because the machine is data, a few questions can be answered by reading it. The lab does this with guards treated as "might pass".
Expected output, captured from a real run (the fifth and sixth scenarios):
=== 5. reading the table without running it
states: [idle, uploading, paused, failed, done]
reachable: [done, failed, idle, paused, uploading]
unreachable: []
dead ends: []
idle accepts [SELECT]
uploading accepts [CANCEL, DONE, FAIL, PAUSE, PROGRESS]
paused accepts [CANCEL, RESUME]
failed accepts [CANCEL, RETRY]
done accepts [RESET]
ignored (state, event) pairs: 34 of 45
flag combinations: 16; machine states: 5
flags after START, FAIL, RETRY, DONE: {"isUploading":true,"isPaused":false,"isFailed":true,"isDone":true} meaningful: false
=== 6. paths found by running the table over sample events (model-based test paths)
key = state only: visited 5, truncated false
done <- SELECT{"name":"a.png","bytes":10}, DONE{"req":1}
failed <- SELECT{"name":"a.png","bytes":10}, FAIL{"req":1,"message":"503"}
idle <- (start)
paused <- SELECT{"name":"a.png","bytes":10}, PAUSE
uploading <- SELECT{"name":"a.png","bytes":10}
key = state + context, limit 40: visited 40, truncated true
- Unreachable states and dead ends. A state no rule leads to is dead code; a state with no way out is usually a bug. Both lists are empty here.
- Accepted events per state. This is the table in one glance, and the place to review a change: a new event type that shows up in the wrong rows is visible at once.
- Ignored pairs. 34 of the 45 (state, event type) pairs have no rule. Printing them turns "silently ignored" into a list a reviewer can read.
- Paths. Breadth-first search over real snapshots, using a list of sample events, finds a shortest event sequence to each state. Replaying each path through the machine ends in its state, and the lab's tests do exactly that. This is the idea of model-based testing: the test cases come from the machine. XState's graph utilities do this at scale: its documentation describes
getShortestPaths(one shortest path to each reachable state, so state coverage) andgetSimplePaths(every non-cyclic path, so transition coverage but possibly many paths). - Unbounded context. The last line is the caveat. With the full snapshot as the key, the request id keeps growing (select, cancel, select, cancel...), so the space is infinite and only the limit of 40 stops the search. The XState graph documentation names the same issue: if context changes with events the state space can be infinite, and by default two states that differ only in context count as different. Keying by state alone is a smaller, approximate model.
What XState does that this lab does not
The lab is flat on purpose. The Stately documentation read for this lesson describes these features of XState, none of which the lab has:
| XState feature (per the Stately documentation) | In the lab |
|---|---|
| Hierarchy: parent states; events go to the deepest active state first, then its parents | One flat level |
| Parallel states: all regions active at once, each receiving every event | None |
| Invoked actors: start on entering a state, stop on exiting it; a pending promise result is discarded on exit | Effects are names; the caller starts and stops things |
Delayed transitions (after), cancelled when the state is exited |
The caller owns timers |
Eventless (always), wildcard (*) and forbidden transitions; reenter |
None |
Tags (state.hasTag), preferred over matches for resilience to change |
State names only |
setup() for typing guards, actions, actors and delays, so send is type-safe |
One table type |
Actors (createActor, subscribe, send) |
A pure step and a loop |
| Path generation and a visual editor (Stately Studio) | A small explore; Mermaid by hand |
Choose a library for hierarchy (a Cancel for every child), parallel regions, timers inside the machine or shared tooling. Choose the plain table for a handful of states when the team would rather read the whole engine. The design work, naming states and deciding the blank cells, is the same.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Flat FSM table | Impossible states cannot exist; ignored events by default; testable | Every blank cell is a decision; state count grows with modes |
| Booleans or a loose reducer | Quick to start | Combinations to police in every handler |
| Guards and context in the machine | Retry limits, request ids and size limits are visible rules | Context can make the state space unbounded for analysis |
| Effects as names | Testable without a network | A caller that must run them and answer with events |
| Library (statecharts) | Hierarchy, parallel regions, actors, tooling | Dependency, vocabulary, behaviour to verify |
Do not use a machine for a two-state toggle, and do not model free-form data (the text in an input) as states: that is context.
Build it
Goal. Run the typed flat machine on the save button and the upload, read its table, and reproduce the stale-response bug.
Setup. The lab is in the course's example workspace (Node 26.13.1). It is pure TypeScript with no React and no DOM; the shared toolchain is installed once for the workspace.
cd examples/frontend/labs/fsm-ui
../../node_modules/.bin/vitest run # 36 tests
../../node_modules/.bin/tsc -p tsconfig.json
node src/demo.ts # golden: examples/frontend/golden/fsm-ui.txt
Steps. Run the tests and the demo and compare it with the outputs above. In src/examples.ts find the fresh guard shared by PROGRESS, FAIL and DONE; in src/fsm.ts find where step returns the same snapshot for an ignored event; then find the cell for DONE in paused.
Verified. The 36 tests passed with Vitest 5.1.0 and the type check (TypeScript 7.0.2) passed, including the four expected type errors. The demo was run twice and its output was identical, and it is the golden file the outputs above were taken from. Nothing was run in a browser or with React.
What the lab does not show. It is not XState and was not compared with it; see the table above. It models time only through events a caller sends, and its guards are plain functions, not named implementations.
Break it. In test/examples.test.ts, the test "finishes the wrong upload when the check is left out (the bug)" builds the machine with guardStale: false. Change that to true and the test fails, because the late DONE is now ignored. Change it back.
In practice: product photo upload in a seller dashboard
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
Sellers on the ShopStream marketplace upload a photo for each product. The component keeps isUploading, isPaused, error and fileName in separate useState calls. Support reports that a seller who cancelled and chose another photo saw "Uploaded" for the new one before it finished, and that Retry stayed enabled after repeated failures (illustrative).
Starting architecture
Figure 5. One flag per concern, handlers that each check the others
How to read this: the warning box owns all the state. Any answer, current or stale, reaches the same handlers, and each handler has to know which flags to set and which to clear.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| More flag checks in each handler | The two reports | More branches | The next event forgets one |
| Abort the old request only | Most late answers | A call per cancel | An answer already in flight still arrives |
| A flat machine with request ids | Both, by construction | A table, guards, tests | Blank cells are decisions |
| A statechart library | Hierarchy, timers in the machine | A dependency | More than five states need |
The decision
| Field | Decision record |
|---|---|
| Context | Flag handlers allow stale answers to finish the wrong upload, and Retry has no limit. |
| Decision | Model the upload as a flat machine with five states, a request id in the context that every response must echo, and a retry guard. Derive the enabled buttons from the machine. Keep effects as names that a small caller runs; abort the request on cancel as well. |
| Consequences, good | Both reports become table rows with tests. The buttons and the rules cannot disagree. |
| Consequences, bad | Every new event needs a decision for every state. |
| Revisit when | The screen needs a parent state, parallel regions (for example several files at once), or timers that belong in the machine. |
Rollout and verification
- Write the table first, with a test per state for accepted and ignored events.
- Print the ignored pairs in review and ask, for each, "is this meant?".
- Replay generated paths as tests, and add the stale-answer story by hand.
- Log (state, event, handled) so a support report can be replayed.
- Check with a keyboard and a screen reader that buttons that turn off do not trap focus; this lab does not test that.
The 2 a.m. failure
Some sellers on fast connections press Pause at 99 percent. The request finishes while the machine is paused, the answer arrives, and the table has no DONE rule in paused, so it is ignored. The seller presses Resume and the screen sits at 99 percent forever. Nothing crashed: the event was ignored exactly as designed (the lab's own first trace shows DONE ignored in paused).
First three checks: (1) in the logs find DONE rows with handled: false in paused; (2) list the table's ignored pairs and look at paused; (3) check whether the caller can finish a request while the UI says paused. Mitigation: accept DONE and FAIL in paused with the same request-id guard, as uploading does. Follow-up: a test for every (state, answer event) pair that can really happen, and a review rule that a new async answer event needs a row in each state a request can be in flight.
Architect's notes
- Name the states before the code. If two states look alike on screen, ask what differs in the next event each accepts.
- Treat blank cells as decisions. Ignore by default is safe only after someone has read the list.
- Put request ids in the context; abort is an optimisation, the id is the correctness.
- Derive the UI from the machine: the view and the enabled buttons.
- Keep data out of the state set. The text in a field is context, not a state.
Common mistakes
- Booleans next to a machine, which bring the impossible combinations back.
- Requests inside the rules, so the machine cannot be tested without a server.
- Forgetting that an ignored event is silent, including the one you meant to handle.
- A guard that does I/O. Guards must be pure and synchronous.
- No request id, so a late answer finishes the wrong request.
- Modelling every keystroke as a state.
- Mutating the context in a rule, which breaks the same-object-means-ignored check.
Key takeaways
- A flat FSM is a table from (state, event) to the next state; it is in one state at a time.
- Events with no rule are ignored, and the same snapshot object comes back.
- Type the table so a missing state, a bad target or an unknown event is a compile error.
- Effects are names; their results come back as events, carrying a request id.
- Derive the view and the enabled buttons from the machine.
- Read the table without running it: reachable states, dead ends, accepted events, ignored pairs.
- Generate test paths from the machine, and expect an unbounded context to make the search infinite.
- Use a statechart library when you need hierarchy, parallel regions or timers inside the machine.
Practice exercises
Exercise 1: Starter (45 min). Draw a login form as a table (idle, submitting, error, signed in) and list the events each state ignores. Then write it as a table for the lab's defineMachine.
Exercise 2: Intermediate (2 hours). Add DONE and FAIL rules to paused with the fresh guard, and write a test that fails before the change and passes after. Re-run the demo and explain the new ignored-pair count.
Exercise 3: Advanced (half day). Add a TIMEOUT event for an upload with no progress. Decide which states accept it, who owns the timer, and which transitions must cancel it. Compare your design with the XState delayed-transitions page.
Related reading
In this course:
- State Machines With XState: parent states, guards, the order of actions and the library.
- Local vs Global State in the Front End: where machine state lives in the app.
- Request Cancellation, Retries and Timeouts: aborting the request the machine named.
- Error, Loading and Empty States: a data screen as a derived view of a few facts.
- Resilient UI and Client Circuit Breakers: limits on retries from the client.
- Form State and Validation: another place where modes and guarded events appear.
Official documentation
- Stately: State machines and statecharts, Machines and States.
- Stately: Transitions, Invoke and Delayed transitions.
- Stately: Parallel states and Graph utilities.
- React: useReducer: pure reducers and the
Object.isbailout. - TypeScript Handbook: Narrowing: the
nevertype and exhaustiveness checking.