State machines

Statecharts, XState, and impossible states made impossible.

Builds on useReducer.

The stores in this part answer where state lives and who re-renders when it changes. They say nothing about which changes are allowed. Any code can set any field to any value at any time, so it's easy to end up with a screen that's loading and showing an error at once, or a form that submits twice.

This chapter is about making invalid states impossible to represent and invalid transitions impossible to perform. You'll start with the "boolean soup" every codebase has, turn it into a discriminated union, see that the useReducer you already know is a small state machine when written the right way, build a table-driven machine from scratch, and then use XState v5 for the cases that need the full power of statecharts.

The problem: boolean soup#

Here's a loader written the way most loaders start. One flag per thing you thought of.

Boolean soup
import { useState } from "react";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string };

let attempt = 0;
// The first request fails, the rest succeed.
const loadBooks = () => fakeFetch("/books", { delay: 600, fail: ++attempt === 1 }) as Promise<Book[]>;

export default function App() {
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [books, setBooks] = useState<Book[] | null>(null);

  async function load() {
    setIsLoading(true);
    try {
      setBooks(await loadBooks());
    } catch {
      setIsError(true);
    }
    setIsLoading(false);
  }

  return (
    <div>
      <button onClick={load}>Load books</button>
      {isLoading && <p>Loading...</p>}
      {isError && <p>Something went wrong.</p>}
      {books && <p>{books.length} books loaded</p>}
    </div>
  );
}

Click Load books: it fails. Click again: for a moment the screen says "Loading..." and "Something went wrong.", then "10 books loaded" and "Something went wrong." Click quickly several times and you start overlapping requests too.

Count the shapes this state can take. Three independent pieces (isLoading, isError, and books being null or not) give 2 × 2 × 2 = 8 combinations. The UI only makes sense in four of them: idle, loading, loaded, failed. The other four are impossible states: combinations the types allow but the product never wants. Every bug above is the app wandering into one of them, because each handler has to remember to reset every other flag.

Make impossible states unrepresentable#

The fix is to stop modeling facts and start modeling states. One field says which state you're in, and each state carries only the data that exists in it. In TypeScript that's a discriminated union: a union of object types that share a literal tag field.

type LoaderState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; books: Book[] }
  | { status: "error"; error: string };

Now "loading and failed" can't be written down. books only exists when status is "success", and TypeScript narrows for you:

switch (state.status) {
  case "success":
    return <BookList books={state.books} />; // books is available here
  case "error":
    return <p>{state.error}</p>;
  // state.books here would be a type error
}

That fixes the states. It doesn't yet stop bad transitions: nothing prevents code from jumping straight from "idle" to "success", or starting a second load while one is running. For that you need rules about which events are allowed in which state. Those rules are a state machine.

What a state machine is#

A finite state machine has:

  • a finite set of states, and it's in exactly one at a time;
  • events that can happen;
  • transitions: for each state, which events it accepts and which state each one leads to;
  • an initial state.

Anything not listed is ignored. If loading doesn't accept FETCH, a second click during loading does nothing. You don't write a guard in the handler. The absence of a transition is the guard.

A state machine for loading books
idleloadingsuccessfailureFETCHonDoneREFRESHonErrorRETRYEvent: start: idle
Step 1 of 6

The machine starts in idle. It's in exactly one state at a time, so it can't be loading and failed at once.

useReducer is a small machine#

A reducer is already (state, event) => nextState. To make it a machine, switch on the current state first, then on the event, and return the same state for anything that isn't allowed. Side effects belong to entering a state: when the machine enters loading, an effect starts the fetch.

A reducer written as a state machine
import { useEffect, useReducer } from "react";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string };
type State =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; books: Book[] }
  | { status: "error"; error: string };
type Event =
  | { type: "FETCH" }
  | { type: "RESOLVE"; books: Book[] }
  | { type: "REJECT"; error: string };

function reducer(state: State, event: Event): State {
  switch (state.status) {
    case "idle":
    case "error":
    case "success":
      return event.type === "FETCH" ? { status: "loading" } : state;
    case "loading":
      if (event.type === "RESOLVE") return { status: "success", books: event.books };
      if (event.type === "REJECT") return { status: "error", error: event.error };
      return state; // FETCH while loading: ignored
  }
}

let attempt = 0;

export default function App() {
  const [state, dispatch] = useReducer(reducer, { status: "idle" });

  // Entering "loading" starts the request. Leaving it ignores a late answer.
  useEffect(() => {
    if (state.status !== "loading") return;
    let ignore = false;
    fakeFetch("/books", { delay: 600, fail: ++attempt === 1 }).then(
      (books) => !ignore && dispatch({ type: "RESOLVE", books }),
      (err) => !ignore && dispatch({ type: "REJECT", error: err.message }),
    );
    return () => {
      ignore = true;
    };
  }, [state.status]);

  return (
    <div>
      <button onClick={() => dispatch({ type: "FETCH" })}>Load books</button>
      <p>
        status: <code>{state.status}</code>
      </p>
      {state.status === "loading" && <p>Loading...</p>}
      {state.status === "error" && <p>Failed: {state.error}</p>}
      {state.status === "success" && <p>{state.books.length} books loaded</p>}
    </div>
  );
}

Click as fast as you like. Extra FETCH events during loading return the same state object, so React bails out of the render and the effect doesn't re-run. The error disappears the moment you retry, because the "error" state and its message are left behind as a unit.

Notice the effect depends on state.status, not on a handler. That's the mapping to keep in mind: effects tied to a state are what XState calls invoked actors. The request lives as long as the machine stays in loading.

Build it: a machine from a table#

A reducer works, but the transitions are buried in if statements. Machines are usually written as data: a table from state to event to target. Here's a tiny interpreter for that table.

A table-driven machine
function createMachine(config) {
  return {
    initial: config.initial,
    transition(state, event) {
      const target = config.states[state]?.on?.[event.type];
      return target ?? state; // not in the table: ignored
    },
    can(state, event) {
      return Boolean(config.states[state]?.on?.[event.type]);
    },
  };
}

const loader = createMachine({
  initial: "idle",
  states: {
    idle: { on: { FETCH: "loading" } },
    loading: { on: { RESOLVE: "success", REJECT: "failure" } },
    success: { on: { REFRESH: "loading" } },
    failure: { on: { RETRY: "loading" } },
  },
});

let state = loader.initial;
for (const type of ["FETCH", "FETCH", "REJECT", "RESOLVE", "RETRY", "RESOLVE", "RETRY"]) {
  const next = loader.transition(state, { type });
  console.log(`${state.padEnd(8)} --${type}--> ${next}${next === state ? "  (ignored)" : ""}`);
  state = next;
}
console.log("can REFRESH now?", loader.can(state, { type: "REFRESH" }));
Nothing logged yet.

Being data, the table can be drawn, checked for unreachable states, and used to generate tests. That's most of what a machine library adds on top: context (extended data like books), actions, guards, invoked side effects, and the statechart features below.

Statecharts: machines that scale#

Flat machines explode as features combine. A media player that can be playing or paused, muted or not, and fullscreen or not needs 2 × 2 × 2 = 8 flat states, and every new feature doubles it. In 1987 David Harel described statecharts, which extend state machines with:

  • Hierarchical (nested) states: checkout.payment.cardEntry. A transition on the parent applies to every child, so "CANCEL from anywhere in checkout" is written once.
  • Parallel states: independent regions active at once. playback and volume each run their own little machine, so 2 + 2 states instead of 2 × 2.
  • Guards: a transition is taken only if a condition holds (RETRY only if fewer than 3 attempts).
  • Actions: fire-and-forget effects on transitions or on entry and exit.
  • Delayed transitions: after: { 5000: "idle" }.
  • History states: return to the child state you were in when you left.
Nested and parallel states (XState config shape)
const player = createMachine({
  type: "parallel",
  states: {
    playback: {
      initial: "paused",
      states: {
        paused: { on: { PLAY: "playing" } },
        playing: { on: { PAUSE: "paused" } },
      },
    },
    volume: {
      initial: "unmuted",
      states: {
        unmuted: { on: { MUTE: "muted" } },
        muted: { on: { UNMUTE: "unmuted" } },
      },
    },
  },
});
// snapshot.value is { playback: "playing", volume: "muted" }

XState v5#

XState is the standard statechart library for JavaScript. Version 5 (the sandbox has xstate 5.33.4 and @xstate/react 6.1.0) is built around two ideas:

  • setup({...}).createMachine({...}): setup declares the named pieces (types, actors, actions, guards) once, so the machine config refers to them by name and TypeScript can check every reference.
  • Everything is an actor. A running machine is an actor: something with its own state that you can only talk to by sending events, and that can be subscribed to. Promises, callbacks and observables can be actors too (fromPromise, fromCallback, fromObservable), and a machine can invoke or spawn child actors.

Here's the books loader with a retry limit, running for real.

XState v5: books loader with a guarded retry
import { useMachine } from "@xstate/react";
import { booksMachine, network } from "./machine";

export default function App() {
  const [snapshot, send] = useMachine(booksMachine);
  const { books, error, retries } = snapshot.context;

  return (
    <div>
      <label>
        <input type="checkbox" defaultChecked={network.fail} onChange={(e) => (network.fail = e.target.checked)} /> Network fails
      </label>
      <p>
        state: <code>{String(snapshot.value)}</code>, retries used: {retries}
      </p>

      {snapshot.matches("idle") && <button onClick={() => send({ type: "FETCH" })}>Load books</button>}
      {snapshot.matches("loading") && <p>Loading...</p>}
      {snapshot.matches("failure") && (
        <p>
          {error}{" "}
          <button disabled={!snapshot.can({ type: "RETRY" })} onClick={() => send({ type: "RETRY" })}>
            Retry
          </button>
        </p>
      )}
      {snapshot.matches("success") && (
        <>
          <button onClick={() => send({ type: "REFRESH" })}>Refresh</button>
          <ul>
            {books.map((b) => (
              <li key={b.id}>{b.title}</li>
            ))}
          </ul>
        </>
      )}
    </div>
  );
}

Load with the network failing, retry twice, and the Retry button disables itself: snapshot.can({ type: "RETRY" }) asks the machine whether the event would cause a transition, guard included. Untick "Network fails" before a retry and it succeeds. The UI never computes "can I retry?" on its own. It asks the machine.

Mapped back to what you built:

Toy and reducerXState v5
the states tablestates: { idle: { on: { FETCH: "loading" } } }
useReducer(reducer, init)useMachine(machine) returns [snapshot, send, actorRef]
state.status === "loading"snapshot.matches("loading")
data inside union memberscontext, updated only through assign
transition(...) !== statesnapshot.can(event)
effect keyed on state.statusinvoke with an actor (fromPromise), stopped automatically on exit
if inside the reducernamed guards

Actors outside React#

The machine doesn't need React at all. createActor(machine).start() runs it anywhere, which makes machines easy to unit test and to share between components or tabs.

import { createActor } from "xstate";

const actor = createActor(booksMachine);
actor.subscribe((snapshot) => console.log(snapshot.value, snapshot.context.retries));
actor.start();
actor.send({ type: "FETCH" });

In React, useMachine creates and starts an actor for the component and re-renders on every snapshot change. When many components need the same actor, or only a slice of it, create it once with useActorRef (or createActorContext to share it through context) and read slices with useSelector(actorRef, (s) => s.context.books.length). That's the selector pattern from Build a store again, because an actor is an external store: subscribe plus get snapshot.

When to reach for XState#

Use a reducer written as a machine for one component's flow. Reach for XState when the flow is the hard part: multi-step wizards, checkout, media players, auth with token refresh, anything with timeouts, retries, cancellation, or parallel regions, and flows product people want to see drawn (the Stately editor visualizes the same config). Don't wrap every toggle in a machine; the ceremony costs more than a boolean that can't go wrong.

Pitfalls#

Check your understanding#

Quick checkCounting states

A form tracks isSubmitting, isSubmitted and hasError as three booleans. How many combinations can it represent, and what's the better model?

PredictEvents a state doesn't accept

What does this log? Write it down, then run it.

import { createMachine, createActor } from "xstate";

const door = createMachine({
  id: "door",
  initial: "closed",
  states: {
    closed: { on: { OPEN: "opened", LOCK: "locked" } },
    opened: { on: { CLOSE: "closed" } },
    locked: { on: { UNLOCK: "closed" } },
  },
});

const actor = createActor(door).start();
for (const type of ["LOCK", "OPEN", "UNLOCK", "OPEN", "LOCK"]) {
  actor.send({ type });
  console.log(type, "->", actor.getSnapshot().value);
}
Nothing logged yet.
Fix itUntangle the loader

The first request fails and the second succeeds. Today the error stays on screen during and after the successful retry. Rewrite the state as one discriminated union (with useState or useReducer) so the screen only ever shows one of: the button alone, "Loading...", "Something went wrong.", or the list.

import { useState } from "react";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string };

let attempt = 0;
const loadBooks = () => fakeFetch("/books", { delay: 150, fail: ++attempt === 1 }) as Promise<Book[]>;

export default function App() {
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [books, setBooks] = useState<Book[] | null>(null);

  async function load() {
    setIsLoading(true);
    try {
      setBooks(await loadBooks());
    } catch {
      setIsError(true);
    }
    setIsLoading(false);
  }

  return (
    <div>
      <button onClick={load}>Load books</button>
      {isLoading && <p>Loading...</p>}
      {isError && <p>Something went wrong.</p>}
      {books && (
        <ul>
          {books.map((b) => (
            <li key={b.id}>{b.title}</li>
          ))}
        </ul>
      )}
    </div>
  );
}
Build itAdd guards to the toy machine

Extend the toy so a transition can be a string target or an object { target, guard }. guard(context, event) returns a boolean; if it returns false, the event is ignored. transition(state, event, context) returns the next state name.

export function createMachine(config) {
  return {
    initial: config.initial,
    transition(state, event, context) {
      // TODO: support { target, guard } as well as a plain string
      const target = config.states[state]?.on?.[event.type];
      return target ?? state;
    },
  };
}
Nothing logged yet.
Explain it out loudWhy a state machine?

An interviewer asks: "When would you use a state machine in a React app, and what does it buy you over useState?"

Interview angle

Say it in 30 seconds

Independent booleans like isLoading and isError multiply into impossible states: three flags allow eight combinations when the UI has four real states. Model state as one status field in a discriminated union so each state carries only its own data. A state machine adds rules: each state lists the events it accepts and everything else is ignored, so double submits and stale errors can't happen. useReducer becomes a small machine when it switches on the current state first. For complex flows, XState v5 adds statechart features: guards, invoked actors, nested and parallel states.

What does 'make impossible states impossible' mean in React state?

basic

How do you write useReducer as a state machine, and where do side effects go?

intermediate

What do statecharts add to plain state machines?

intermediate

What's the actor model in XState v5, and how does it connect to React?

senior

When is XState worth it, and when is it overkill?

senior

What happens when you send an XState machine an event its current state doesn't handle?

basic

Recap#

  • Independent booleans multiply into impossible states. One status field in a discriminated union makes them unrepresentable, and carries each state's data with it.
  • A state machine adds transitions: each state lists the events it accepts, and everything else is ignored. That turns double submits and stale errors into non-events.
  • useReducer is a machine when it switches on the current state first and returns the same state for disallowed events. Start side effects from being in a state.
  • Statecharts add nesting, parallel regions, guards, actions, delays and history, so flows stay manageable as features combine.
  • XState v5: setup({ types, actors, actions, guards }).createMachine(config), useMachine for [snapshot, send], snapshot.matches and snapshot.can, invoked fromPromise actors, and createActor to run machines without React.

Sources#