Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 132 ยท Advanced Patterns

State Machines in React

Model React UI with finite state machines - replace boolean flags with named states, write transitions as a reducer, prevent impossible states, handle async flows and timeouts, and know when to use XState.

Open any large React codebase and you will probably find a component with state like isLoading, isError, isSubmitting, isSuccess, isDisabled and hasRetried. Each flag is simple. Together they allow 2^6 = 64 combinations, but only a handful of those combinations are meaningful. The rest are impossible states: "loading and failed at the same time", "success but still submitting". Nothing in the code forbids them, so sooner or later a bug creates one and the screen shows nonsense.

A finite state machine is the cure. You list the few states your UI can be in, list the events that can happen, and write down which event moves you from which state to which. Anything not written down cannot happen. This lesson shows how to get there step by step with plain React (useReducer), how to handle async work and timeouts, and when a library such as XState is worth adding.

The problem: boolean soup

Look at a typical data-loading component:

JSX
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [data, setData] = useState(null);

Three variables, and the render has to guess the meaning of every combination. Here is what one forgotten reset does:

Impossible states with boolean flags

Press Load, then Fail: the page says Loading... Error: network down at the same time. Press Succeed and you get all three messages at once. Every handler has to remember to reset the other flags, and nothing complains when one doesn't. As flags are added, the number of "reset everything else" lines grows quadratically.

The root cause: three independent variables are describing one thing, the status of a request. The fix is to describe it with one variable that can only be in one state at a time.

States, events and transitions

A state machine has four ingredients:

  1. States: a fixed, named set. For a request: idle, loading, success, error.
  2. Events: things that happen. FETCH, RESOLVE, REJECT, RETRY.
  3. Transitions: a rule "in state S, event E leads to state T".
  4. Context (extended state): the data that travels along, like the loaded rows or the error message. The state names say what is happening, the context carries the details.

A neat way to write transitions is a plain object, a transition table:

JavaScript
const transitions = {
  idle:    { FETCH: 'loading' },
  loading: { RESOLVE: 'success', REJECT: 'error' },
  success: { FETCH: 'loading' },
  error:   { RETRY: 'loading' },
};

Read it as a lookup: transitions[currentState][event] gives the next state, or undefined when the event is not allowed there. That single rule gives you the machine's most valuable property: events that do not make sense are ignored. A double-click on Submit sends SUBMIT while already submitting; the table has no entry, so nothing happens.

A reducer is already a machine

React's useReducer has the exact shape needed: (state, action) => nextState (see useReducer and Reducers). A state machine is a reducer where the next state depends on both the current state's name and the event.

A request machine as a reducer

Experiment with the buttons. FETCH moves from idle to loading; pressing RETRY at that moment prints ignored RETRY while loading in the console and the status stays put; RESOLVE shows the data, REJECT shows the message. You cannot reach "loading and error" because there is no such state. A mistake in the transition table is also easy to spot, since the whole behavior fits in one object you can read at a glance.

Two details of the reducer are worth copying:

  • Returning the same object current for an ignored event tells React nothing changed, so it skips the render.
  • The reducer stays pure. It doesn't start requests or timers; it only computes the next state. Side effects belong in handlers or effects that send events (next sections).

Name states after what the user sees or what the system is doing (submitting, editing, confirmingDelete), not after the booleans you used to have. Name events in the past tense or as facts (SUBMITTED, TIMED_OUT, CLOSE_CLICKED) rather than as commands that assume a result. A good state name reads aloud in the sentence "The form is ___".

Async flows: events from effects

Real flows include waiting. The machine does not wait; an effect does the waiting and then sends an event. The pattern:

  1. An event moves the machine into a state like submitting.
  2. An effect that depends on status === 'submitting' starts the work.
  3. When the work finishes, the effect sends RESOLVE or REJECT.
  4. The effect's cleanup cancels the work if the machine leaves submitting early (for example on CANCEL).
Submit, retry and cancel

Press Submit. The console prints request #1 started, and after a moment the status becomes error and request #1 cleaned up appears (the effect re-ran because status changed, so the old one cleans up). Press Retry: request #2 started, then success and the "Saved!" message. If you press Cancel while submitting, the cleanup clears the timer, so a late answer can never arrive for a request the user abandoned. That is exactly the stale-response problem from Async Patterns and Race Conditions, made structurally impossible: the machine and the effect agree.

Notice also the buttons: disabled={status !== 'idle'} is derived from the state name. Each button is available exactly where the transition table has an entry for its event. You never wrote isSubmitting anywhere.

Timeouts as transitions

Time is just another event source. "If the server doesn't answer within N ms, give up" becomes a second timer in the effect that sends TIMEOUT, plus one line in the table: loading: { TIMEOUT: 'error' }. Whichever event arrives first wins; the other one arrives in a state where it has no meaning and is ignored.

A request with a timeout

With 50 ms selected, Start ends in done. Choose 400 ms and Start ends in timedOut after about 150 ms. When either event arrives, the state changes, the effect cleans up both timers, and the loser can never fire. The messages lookup keyed by state name is a good habit: every state must have a message, and a missing key is an obvious bug.

The reducer here uses the event as a plain string (send('START')) since there is no payload; use objects like { type, ... } when events carry data.

Timers in this lesson use 50 to 400 milliseconds so the examples finish quickly. In a real app the numbers would be seconds. The machine does not change, only the delays do.

Guards, context and a reusable hook

Sometimes an event is allowed only if a condition holds: "go to the next step only if the name is filled in". That condition is a guard. In the table style you can allow a transition to be a function:

JavaScript
NEXT: (context) => (context.name.trim() !== '' ? 'address' : undefined)

Returning undefined means "not allowed" and the machine stays where it is. The next example wraps the reducer plumbing in a tiny useMachine hook that also exposes can(event), so the UI can disable what is not possible, and builds a three-step wizard with it.

A checkout wizard with guards

On the first step, Next is disabled until you type a name; the guard returns undefined for an empty name. Type one and Next lights up. On the address step, Back and Next appear in the right combinations, on the review step only Back and Confirm work, and on the last step nothing is enabled, since done has no transitions: it is a final state. The status string decides which fields render, so a half-visible form (name field and review text at once) cannot exist.

The hook is deliberately small. It does not run effects or parallel states or delayed transitions; for that you would reach for a library.

When to reach for XState

XState is the best-known JavaScript statechart library. It adds what the hand-rolled version lacks: nested (hierarchical) states, parallel states, built-in delayed transitions and timers, invoked services (promises, callbacks), history states, a visual editor and inspector, and strong TypeScript types. The request machine from earlier looks like this (read-only, because XState is not installed in our editor):

JavaScript
import { setup, assign, fromPromise } from 'xstate';
import { useMachine } from '@xstate/react';

const requestMachine = setup({
  actors: {
    load: fromPromise(() => fetch('/api/report').then((response) => response.json())),
  },
}).createMachine({
  id: 'request',
  initial: 'idle',
  context: { data: null, message: null },
  states: {
    idle: { on: { FETCH: 'loading' } },
    loading: {
      invoke: {
        src: 'load',
        onDone: { target: 'success', actions: assign({ data: ({ event }) => event.output }) },
        onError: { target: 'error', actions: assign({ message: ({ event }) => String(event.error) }) },
      },
      after: { 5000: 'error' },
    },
    success: { on: { FETCH: 'loading' } },
    error: { on: { RETRY: 'loading' } },
  },
});

function Report() {
  const [snapshot, send] = useMachine(requestMachine);
  return <button onClick={() => send({ type: 'FETCH' })}>{String(snapshot.value)}</button>;
}

The structure matches the table you wrote by hand: states, events, targets, context. The library handles the promise, the 5 second timeout (after) and cleanup for you. Details of the API change between major versions, so check the current documentation before copying.

A practical guide:

Situation Choice
3 to 6 states, a few events A transition table with useReducer (as above)
Wizards, dialogs, tabs, form submit states useReducer machine
Nested or parallel behavior (a player that is playing and also muted and also buffering) XState
Many timers, invoked promises, long-lived flows, need to visualize or share the model with designers XState
Server data with caching A data library, not a hand-built machine (see Caching and Server State)

You don't need a library to benefit from the way of thinking. Even a status string with four values is a vast improvement over four booleans.

Practical advice

  • Start by listing the states on paper, then the events. Drawing boxes and arrows takes five minutes and finds missing cases (what happens if the user closes the dialog while saving?).
  • Keep one status and move everything else into context. Never mirror state names in other state variables.
  • Derive instead of storing. isLoading is just status === 'loading'; compute it where needed.
  • Make impossible transitions impossible, not "handled with if statements" across five handlers.
  • Put side effects in effects or handlers that react to the state, never in the reducer. Clean them up when the state leaves.
  • Remember StrictMode. If you wrap the app in <StrictMode>, development runs the setup, cleanup, setup cycle for effects (Cleanup, Subscriptions and Timers). Machine effects that start timers and clear them in cleanup survive that cycle by design.
  • Use switch (status) or lookup objects for rendering. If you forget a case, make the fallback throw, so a new state cannot silently render nothing.
  • Don't force it. A simple on/off toggle does not need a machine. Use one when you see two or more booleans that depend on each other.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is an impossible state?

    Independent boolean flags allow combinations that make no sense together. A single status value that can only hold one named state at a time rules them out.
  2. 2. In the transition-table machine, what happens when an event has no entry for the current state?

    The lookup returns undefined, the reducer returns the existing state, and nothing happens. A double click on Submit while submitting is therefore harmless.
  3. 3. Where should the timer for an async or timeout transition be started?

    Reducers must be pure. An effect keyed on the status starts the work and sends the resulting event, and cleanup cancels it if the machine leaves that state first.
  4. 4. What is a guard in a state machine?

    A guard returns whether an event may fire in the current context, such as allowing NEXT only when a required field is filled in. A state with no transitions is a final state.
  5. 5. Which situation is the strongest reason to choose XState over a hand-written reducer?

    Hierarchical and parallel states, delayed transitions and invoked services are what a statechart library provides. For a handful of states a transition table in useReducer is enough.

Summary

  • Several booleans that describe the same thing allow impossible combinations; replace them with one status that has named states.
  • A machine is states + events + transitions (+ context). A plain object table such as transitions[status][event] is enough; unknown events are ignored.
  • useReducer is a natural home for a machine because the reducer computes the next state purely.
  • Start async work and timers in effects keyed on the state; send events when they finish, and clean up when the state changes.
  • Guards allow a transition only when a condition holds, and can(event) lets the UI disable what the machine would reject.
  • Use XState when you need nested or parallel states, delayed transitions, invoked services or visual tooling; otherwise a hand-rolled machine is plenty.

Next: Accessibility in React