When should a UI workflow be modeled as a state machine?
Use explicit states and transitions when async workflows have mutually exclusive phases and guarded actions.
Useful prerequisites
A checkout form might be idle, validating, submitting, complete or failed. If the application represents all of that with a handful of booleans, combinations that should never happen become possible. A state machine makes the allowed states and transitions explicit, so the interface has fewer ways to get stuck in an impossible condition.
A checkout form might be idle, validating, submitting, complete or failed. If the application represents all of that with a handful of booleans, combinations that should never happen become possible. A state machine makes the allowed states and transitions explicit, so the interface has fewer ways to get stuck in an impossible condition.
The quick version
A state machine is useful when a workflow has meaningful states, events, and transition rules that are difficult to express safely with unrelated booleans. It makes valid transitions explicit and impossible combinations harder to represent.
Build the mental model
Three booleans such as isLoading, hasError, and isComplete allow contradictory combinations. A discriminated union can model the same invariant at the type level.
See it in code
type UploadState =
| { status: 'idle' }
| { status: 'uploading'; progress: number }
| { status: 'failed'; message: string }
| { status: 'complete'; fileId: string };
Where it gets tricky
Transitions should define guards and side effects separately. A delayed response from a previous state must not move the workflow backward after cancellation or restart. Model retry as a transition with an attempt count and a terminal policy. Test invalid events explicitly; an impossible transition should be rejected or logged rather than silently ignored.
A common misunderstanding
Not every toggle needs a formal state-machine library.
What this changes in an application
Use explicit transitions for checkout, uploads, auth, multi-step forms, and retry workflows. Include cancellation, stale events, and unexpected transition tests.
Questions worth exploring next
- How do you model retries?
- What should happen if a completion event arrives after cancellation?
References and next steps
- Stately state machines — primary or authoritative documentation for the underlying behavior.
- MDN Web Docs — use the relevant API reference for adjacent browser details.