Skip to content
jshacks.dev
Patterns

State Machines in JavaScript: From switch to XState

A state machine lists the states a thing can be in and the moves between them. See it built with a switch, an object table and XState 5, with tests.

8 min read
Summarize in AI
Flat illustration of a staircase from one version to the next, with the JavaScript, Node.js and TypeScript logos.

A state machine describes something as being in exactly one of a fixed set of states, with a fixed set of events that move it from one state to another. A traffic light, a payment, a file upload and a modal dialog are all state machines, whether or not the code says so. When it does not say so, the state lives in a handful of booleans, isLoading, hasError, isSubmitted, and combinations that should be impossible, such as loading and failed at once, are reachable by accident. This post shows how to make the machine explicit in JavaScript on Node.js 24: first with a plain switch, then a transition table, then XState 5, the most widely used library. It covers guards, side effects, testing and when a machine is more than you need. Every sample prints its output.

The boolean soup

Here is the state of a form submission tracked by flags.

flags.mjsJavaScript
const form = { isSubmitting: false, isSuccess: false, hasError: false };

function submitStart() {
  form.isSubmitting = true;
}
function submitFail() {
  form.isSubmitting = false;
  form.hasError = true;
}
function submitOk() {
  form.isSubmitting = false;
  form.isSuccess = true;
}

submitStart();
submitFail();
submitStart();
submitOk();
console.log(form);
Text
{ isSubmitting: false, isSuccess: true, hasError: true }

The form is now both successful and in error. Three booleans allow eight combinations and perhaps four of them are meaningful. Every if in the interface must guess which combination it is looking at, and the bug above came from forgetting to reset hasError on retry. A state machine removes the impossible combinations by having a single status value.

Level one: a switch

Replace the flags with one variable and a function that returns the next state.

switch-machine.mjsJavaScript
function transition(state, event) {
  switch (state) {
    case "idle":
      if (event === "SUBMIT") return "submitting";
      return state;
    case "submitting":
      if (event === "SUCCESS") return "success";
      if (event === "FAILURE") return "error";
      return state;
    case "error":
      if (event === "SUBMIT") return "submitting";
      return state;
    case "success":
      return state;
    default:
      throw new Error(`Unknown state: ${state}`);
  }
}

let state = "idle";
for (const event of ["SUBMIT", "FAILURE", "SUBMIT", "SUCCESS", "SUBMIT"]) {
  state = transition(state, event);
  console.log(`${event} -> ${state}`);
}
Text
SUBMIT -> submitting
FAILURE -> error
SUBMIT -> submitting
SUCCESS -> success
SUBMIT -> success

The final SUBMIT was ignored, because success has no transition for it. Impossible combinations cannot occur since there is only one variable. Retrying from error goes back to submitting, which clears the error by construction, so the earlier bug cannot happen. The function is pure and trivial to test: pass a state and an event, assert the result.

Level two: a transition table

As states grow, nested switch statements get long. Moving the rules into data makes the machine readable at a glance and lets you inspect it.

table-machine.mjsJavaScript
const machine = {
  initial: "idle",
  states: {
    idle: { SUBMIT: "submitting" },
    submitting: { SUCCESS: "success", FAILURE: "error" },
    error: { SUBMIT: "submitting" },
    success: {},
  },
};

export function next(state, event) {
  return machine.states[state][event] ?? state;
}

export function can(state, event) {
  return event in machine.states[state];
}

console.log(next("idle", "SUBMIT"));
console.log(next("success", "SUBMIT"));
console.log(can("error", "SUBMIT"), can("success", "SUBMIT"));
console.log(Object.keys(machine.states));
Text
submitting
success
true false
[ 'idle', 'submitting', 'error', 'success' ]

can answers questions the interface needs, such as whether to enable a Retry button, from the same table that drives behavior. The two cannot disagree because there is only one source. The table is also data, so a script can draw it as a diagram or check it for states with no way out.

Guards and context

Real machines carry data beside the state, called context, and some transitions are allowed only when a condition holds, called a guard. A retry limit is the classic example.

guards.mjsJavaScript
function transition({ status, attempts }, event) {
  switch (status) {
    case "idle":
      return event === "SUBMIT" ? { status: "submitting", attempts: attempts + 1 } : { status, attempts };
    case "submitting":
      if (event === "SUCCESS") return { status: "success", attempts };
      if (event === "FAILURE") {
        return attempts >= 3 ? { status: "failed", attempts } : { status: "error", attempts };
      }
      return { status, attempts };
    case "error":
      return event === "RETRY" ? { status: "submitting", attempts: attempts + 1 } : { status, attempts };
    default:
      return { status, attempts };
  }
}

let state = { status: "idle", attempts: 0 };
for (const event of ["SUBMIT", "FAILURE", "RETRY", "FAILURE", "RETRY", "FAILURE"]) {
  state = transition(state, event);
  console.log(event, state);
}
Text
SUBMIT { status: 'submitting', attempts: 1 }
FAILURE { status: 'error', attempts: 1 }
RETRY { status: 'submitting', attempts: 2 }
FAILURE { status: 'error', attempts: 2 }
RETRY { status: 'submitting', attempts: 3 }
FAILURE { status: 'failed', attempts: 3 }

After the third attempt the guard attempts >= 3 routes failure to a terminal failed state instead of error. The rule is stated once, in the transition, not scattered through click handlers.

Level three: XState 5

By this point you are reimplementing features a library already has: nested states, parallel regions, delayed transitions, side effects and visualization. XState is the established library, and version 5 uses setup() and createMachine().

xstate.mjsJavaScript
import { createMachine, createActor, assign } from "xstate";

const submitMachine = createMachine({
  id: "submit",
  initial: "idle",
  context: { attempts: 0 },
  states: {
    idle: { on: { SUBMIT: { target: "submitting", actions: assign({ attempts: ({ context }) => context.attempts + 1 }) } } },
    submitting: {
      on: {
        SUCCESS: "success",
        FAILURE: [
          { guard: ({ context }) => context.attempts >= 3, target: "failed" },
          { target: "error" },
        ],
      },
    },
    error: { on: { RETRY: { target: "submitting", actions: assign({ attempts: ({ context }) => context.attempts + 1 }) } } },
    success: { type: "final" },
    failed: { type: "final" },
  },
});

const actor = createActor(submitMachine);
actor.subscribe((snapshot) => {
  console.log(snapshot.value, snapshot.context.attempts);
});
actor.start();

for (const type of ["SUBMIT", "FAILURE", "RETRY", "SUCCESS"]) actor.send({ type });
Text
idle 0
submitting 1
error 1
submitting 2
success 2

The declarative definition holds the same guard and counter. subscribe receives every snapshot, including the initial one, which is why the first line shows idle 0. Check the current XState documentation for the exact API of the version you install, since the library's setup helpers have changed between major releases.

What the library adds beyond the hand-written version:

  • Side effects as declared actions and invoked services, so a state can start a fetch on entry and cancel it on exit, with the result arriving as an event.

  • Hierarchical states, where editing contains valid and invalid, and an event on the parent applies to all children.

  • Parallel states, for independent regions such as a media player's playback and volume.

  • Visualization and inspection, since the definition is data a tool can render.

  • Delayed transitions, such as returning to idle after a timeout.

Testing machines

Because transitions are deterministic, tests are a list of event sequences and expected states. You do not need a browser or a DOM for any of it.

machine-test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";
import { next } from "./table-machine.mjs";

test("a failed submission can be retried and then succeeds", () => {
  const path = ["SUBMIT", "FAILURE", "SUBMIT", "SUCCESS"].reduce(next, "idle");
  assert.equal(path, "success");
});

test("a finished form ignores further submits", () => {
  assert.equal(next("success", "SUBMIT"), "success");
});
Text
✔ a failed submission can be retried and then succeeds (0.9ms)
✔ a finished form ignores further submits (0.2ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

You can also generate tests by walking every reachable state and every event, which catches missing transitions. XState's @xstate/graph package does this.

Using a machine in a UI

In React, a machine replaces a pile of useState calls. The component renders from the current state value and sends events from handlers, so the interface cannot show an impossible combination.

SubmitButton.jsxJSX
import { useMachine } from "@xstate/react";
import { submitMachine } from "./submit-machine.js";

export function SubmitButton() {
  const [snapshot, send] = useMachine(submitMachine);

  if (snapshot.matches("success")) return <p>Saved</p>;
  return (
    <button disabled={snapshot.matches("submitting")} onClick={() => send({ type: "SUBMIT" })}>
      {snapshot.matches("submitting") ? "Saving" : "Save"}
    </button>
  );
}

Disabling the button during submitting follows from the state, not from a separate flag that someone might forget to set.

When a machine is more than you need

Two states and one event is a boolean, and a boolean is fine. A machine pays for itself when you notice three things: several flags that must change together, bugs of the form "this combination should never happen", or a flow with retries, timeouts and cancellation. Start with the switch. Move to a table when the rules need to be read or inspected. Adopt XState when you need nesting, parallel regions or managed side effects, since it brings a dependency and a vocabulary your team must learn.

Where the advice stops

State machines model discrete states well and continuous values poorly. A slider position or a text field's contents belong in context, not in states, and a machine with a state per value is a sign you modeled the wrong thing. Also avoid state explosion: a machine with forty states and four hundred transitions is hard to read. Use hierarchy and parallel regions to keep each machine small, and split unrelated flows into separate machines that talk by events.

Drawing the machine

One of the quiet benefits of a table or a library definition is that you can draw it. A diagram of states as boxes and events as arrows is the quickest way to review a flow with someone who does not read code, such as a designer or a product manager. They can see at a glance that success has no outgoing arrows, or that nothing returns from failed, and ask whether that is intended. Many bugs are found at this stage, before a line of interface code exists. A few lines of script can turn the table above into a Mermaid or Graphviz description, and XState's inspector draws its own diagram from the definition.

Migrating an existing component

You can introduce a machine into a component that already works. List the states a user can see, such as idle, loading, loaded and failed, by looking at what the interface renders. Map each existing flag combination to one of those states, and note any combination that maps to none, since those are latent bugs. Then replace the flags with a single status value and update the handlers to send events. Keep the interface's markup the same, so the change is easy to review, and write the transition tests before you start, so you know behavior did not move.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.