Finite State Machines for UI
Replaces overlapping boolean flags (isLoading, isError, isRetrying) with a discriminated union and explicit (state, event) transition table that makes invalid states unrepresentable.
About this page
State Modeling: 4 Booleans (16 States) vs FSM (4 States)
Compare error-prone boolean flags against an explicit discriminated-union transition table.
if (isLoading && !isError && isSuccess) {
// How did we get here? Forgot to reset isSuccess on retry.
}
setIsLoading(true); // forgot setIsError(false)!Spinner and error toast can render at the same time; double-clicks fire duplicate requests.
const transitions = {
idle: { FETCH: 'loading' },
loading: { RESOLVE: 'success', REJECT: 'error' },
error: { RETRY: 'loading' }
};FETCH in 'loading' state is structurally ignored—zero double-submits.
Under the Hood#
Boolean flags act like four light switches wired to one bulb: nothing stops code from flipping isLoading and isError on together. A Finite State Machine works like a rotary dial, only one position is active, blocking Optimistic UI races and Stale Closures.
- Finite states: Enumerate every legal mode (
idle | loading | success | error) as a tagged union. - Events: Represent triggers as explicit objects (
{ type: 'SUBMIT' }) rather than ad-hoc setter calls. - Transition function: A pure
transition(state, event)checks the current state first, ignoring any event not valid for that state.
type State = { status: 'idle' } | { status: 'loading' } | { status: 'error'; message: string };
type Event = { type: 'FETCH' } | { type: 'FAIL'; message: string } | { type: 'RESET' };
function transition(state: State, event: Event): State {
if (state.status === 'idle' && event.type === 'FETCH') return { status: 'loading' };
if (state.status === 'loading' && event.type === 'FAIL') return { status: 'error', message: event.message };
if (state.status === 'error' && event.type === 'RESET') return { status: 'idle' };
return state; // Invalid event for current state is safely ignored
}Problem Genealogy#
- 1987 (David Harel Statecharts): Formalized hierarchical and parallel state machines for avionics and embedded UIs.
- 2015 (Redux Reducers): Popularized
(state, action) => nextState, though teams still storedisLoading/isErrorbooleans inside the state object. - 2018+ (XState & Tagged Unions): Brought strict TypeScript discriminated unions and W3C SCXML statecharts to frontend workflows.
Production Pitfalls#
- Event explosion on simple toggles: Writing a 60-line statechart configuration for an open/closed disclosure panel adds ceremony with zero safety gain.
- Forgetting cleanup on state exit: Cancelling an in-flight
AbortControllerwhen leavingloading->idlemust happen deterministically on transition, or stale responses still land.
Where this connects
Prerequisites
Optimistic UI & Rollback Safety
Modeling pending, confirmed, and rolled-back phases as finite states prevents double-mutations.
Next & related
Hierarchical Statecharts & UI Actor Model
Hierarchical statecharts extend flat (state, event) transition tables with nested compound states and orthogonal regions.
Stale Closures in Hooks & Callbacks
Pure (state, event) => nextState reducers evaluate transitions cleanly without closing over stale flags.
Seen in Architecture Autopsies
Autopsy #01: Double Payment on a Disabled Button
Boolean flags (isLoading, hasError) permit re-entry after a timeout while the first request remains in flight.
Mechanical Comparisons
- Contrasts WithSignals and Fine-Grained Reactivity (Reactive Graph) vs Finite State Machines for UI
Signals propagate arbitrary reactive value changes, whereas finite state machines enforce explicit transition guards.
- Contrasts WithFinite State Machines for UI vs Stale Closures in Hooks & Callbacks
Pure (state, event) => nextState reducers evaluate transitions cleanly without closing over stale flags.