Skip to content

State Machines

The Course
•
20 min study

A timer that can be ready, focusing, paused or on a break has rules: you can't pause something that hasn't started, or resume something that isn't paused. With a few booleans, such as isRunning and isPaused, those rules are spread through the event handlers, and sooner or later two flags disagree. A state machine writes the rules down in one place.

A Pomodoro machine React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useReducer } from "react"; import { can, transition } from "./machine.js"; const labels = { idle: "Ready", focusing: "Focusing", paused: "Paused", onBreak: "On a break" }; const events = ["START", "PAUSE", "RESUME", "FINISH", "RESET"]; function reducer(status, event) { const next = transition(status, event); console.log(`${status} + ${event} → ${next}`); return next; } export default function App() { const [status, send] = useReducer(reducer, "idle"); return ( <main> <h1>Pomodoro: {labels[status]}</h1> <div className="toolbar"> {events.map((event) => ( <button key={event} onClick={() => send(event)} disabled={!can(status, event)}> {event.toLowerCase()} </button> ))} </div> </main> ); } // The timer as a state machine: every state lists the events it accepts, and // where each one leads. Anything not listed is ignored. export const machine = { idle: { START: "focusing" }, focusing: { PAUSE: "paused", FINISH: "onBreak", RESET: "idle" }, paused: { RESUME: "focusing", RESET: "idle" }, onBreak: { FINISH: "idle", RESET: "idle" }, }; export function transition(status, event) { return machine[status][event] ?? status; } export function can(status, event) { return event in machine[status]; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Click through the buttons and watch the console.

The machine

JavaScript
export const machine = {
  idle: { START: "focusing" },
  focusing: { PAUSE: "paused", FINISH: "onBreak", RESET: "idle" },
  paused: { RESUME: "focusing", RESET: "idle" },
  onBreak: { FINISH: "idle", RESET: "idle" },
};

Each state lists the events it accepts, and the state each one leads to. That's the whole set of rules. transition(status, event) looks the next state up, and returns the same state for an event that isn't listed:

JavaScript
export function transition(status, event) {
  return machine[status][event] ?? status;
}

export function can(status, event) {
  return event in machine[status];
}

Everything follows from the table

  • The reducer is just transition. There are no ifs in it:

    JavaScript
    function reducer(status, event) {
      const next = transition(status, event);
      console.log(`${status} + ${event} → ${next}`);
      return next;
    }
  • The buttons ask the machine: disabled={!can(status, event)}. They can never offer something the machine would ignore.

  • Impossible states are impossible. status is one string, so "paused and on a break" can't be represented.

Predict

The disabled buttons hide the machine's other safeguard. Add a button that is always enabled, <button onClick={() => send("RESUME")}>Force resume</button>, and press it while the timer is Ready. What does the console say?

Check your prediction

idle + RESUME → idle. The machine ignores an event its current state doesn't list, so a stray event can't push it somewhere invalid. A boolean version would happily set isRunning = true from anywhere.

When to use one

Reach for an explicit machine when a feature has several modes with rules between them: a timer, an upload, a checkout, a multi-step form, a media player. For bigger machines, with nested states, guards and delays, libraries such as XState give you the same idea with more tools.

Exercise

A long break every fourth session

Real Pomodoro timers give a long break after every fourth focus session. That needs the machine to remember data, not just which state it's in.

  • Count completed focus sessions, and show Sessions completed: 2 under the heading. A session counts only when finish ends it, not reset.
  • After every fourth completed session, finish leads to a new state, longBreak, labelled On a long break, instead of onBreak. From longBreak, FINISH and RESET both go to idle.
  • machine.js stays the one place that says which events each state accepts.

After four rounds of start, finish, finish, the fourth round's first finish should log:

Text
focusing + FINISH → longBreak
Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useReducer } from "react"; import { can, transition } from "./machine.js"; const labels = { idle: "Ready", focusing: "Focusing", paused: "Paused", onBreak: "On a break" }; const events = ["START", "PAUSE", "RESUME", "FINISH", "RESET"]; function reducer(status, event) { const next = transition(status, event); console.log(`${status} + ${event} → ${next}`); return next; } export default function App() { const [status, send] = useReducer(reducer, "idle"); return ( <main> <h1>Pomodoro: {labels[status]}</h1> <div className="toolbar"> {events.map((event) => ( <button key={event} onClick={() => send(event)} disabled={!can(status, event)}> {event.toLowerCase()} </button> ))} </div> </main> ); } // The timer as a state machine: every state lists the events it accepts, and // where each one leads. Anything not listed is ignored. export const machine = { idle: { START: "focusing" }, focusing: { PAUSE: "paused", FINISH: "onBreak", RESET: "idle" }, paused: { RESUME: "focusing", RESET: "idle" }, onBreak: { FINISH: "idle", RESET: "idle" }, }; export function transition(status, event) { return machine[status][event] ?? status; } export function can(status, event) { return event in machine[status]; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

The table can say which events a state accepts and where they usually lead, but not "every fourth time": that depends on a number the status string doesn't hold. Machines keep such data next to the status, as extended state, and use it in a guard, a condition that chooses between two targets for the same event.

Hint 2: a first step

Make the reducer's state an object with status and completed, starting at "idle" and 0, and change the heading and the buttons to read state.status. Everything should behave exactly as before: that proves the refactor. Then find the one transition that needs the count, focusing + FINISH, and handle it in the reducer. Don't forget the table entry for the new state.

Show one solution

In machine.js, add the new state. focusing still lists FINISH: "onBreak", the usual target:

JavaScript
longBreak: { FINISH: "idle", RESET: "idle" },

In App.jsx:

JavaScript
const labels = { idle: "Ready", focusing: "Focusing", paused: "Paused", onBreak: "On a break", longBreak: "On a long break" };

function reducer(state, event) {
  let next = transition(state.status, event);
  let completed = state.completed;
  if (state.status === "focusing" && event === "FINISH") {
    completed += 1;
    if (completed % 4 === 0) next = "longBreak";
  }
  console.log(`${state.status} + ${event} → ${next}`);
  return { status: next, completed };
}
JSX
const [state, send] = useReducer(reducer, { status: "idle", completed: 0 });
JSX
<h1>Pomodoro: {labels[state.status]}</h1>
<p className="muted">Sessions completed: {state.completed}</p>

and can(state.status, event) for the buttons. The table still decides whether FINISH is allowed at all; the guard only picks between two targets once it is. The On Your Own drill on Day 7 needs the same pattern: a machine that carries an index and a score alongside its status.

Was this article helpful?

Your response is saved on this device.