← Back to JavaScript, page 10

javascript-0196 · Hard senior

How do you model UI or async flows with a finite state machine, and what problems does it solve compared with boolean flags?

A finite state machine lists the allowed states and the events that move between them, so impossible combinations such as loading and error at the same time cannot exist. Define a transition table with optional guards and actions, reject unknown events, and make state changes go through one function. This makes flows easy to test, draw, and extend.

Full answer

Many UI bugs come from independent boolean flags: isLoading, hasError, isSuccess. Four booleans can have 16 combinations, but only a few are valid. A state machine replaces them with one status value from a small set, and lets only the defined transitions happen.

Parts of a machine:

  • States: idle, loading, success, error. The set is finite and named.
  • Events: FETCH, RESOLVE, REJECT, RETRY, RESET.
  • Transitions: a table { state: { event: nextState } }. An event that is not listed for the current state is ignored or reported as an error. For example, FETCH while loading does nothing, so double submit bugs disappear.
  • Guards: conditions that must be true for a transition, such as retries < 3.
  • Actions (effects): code that runs on entering, leaving, or on a transition, such as starting a request or setting a timer. Keep the transition function pure and run effects outside it, or return a description of the effects.
  • Context (extended state): data that goes along with the state, such as the retry count and the last error.
  • Hierarchical and parallel states (statecharts) handle larger flows, for example a form that is editing while another region manages saving.

Benefits: a single place for the rules, invalid states cannot be represented, easy testing (given state and event, expect next state), and diagrams for communication. Libraries include XState, Robot, and reducers with a status field.

Costs: more code for small flows, and a learning curve. A simple toggle does not need a machine. A good test is whether more than two flags depend on each other.

Also useful for: multi-step wizards, checkout, media players, drag and drop, authentication, and connection handling (like reconnecting sockets).

javascript
function createMachine({ initial, context, states, onTransition }) {
  let state = initial;
  let ctx = { ...context };
  const listeners = [];
  return {
    get state() { return state; },
    get context() { return ctx; },
    can: (event) => Boolean(states[state].on?.[event]),
    send(event, payload) {
      const transition = states[state].on?.[event];
      if (!transition) {
        onTransition?.({ ignored: event, state });
        return false;
      }
      const options = Array.isArray(transition) ? transition : [transition];
      const chosen = options.find((option) => !option.guard || option.guard(ctx, payload));
      if (!chosen) {
        onTransition?.({ blocked: event, state });
        return false;
      }
      const from = state;
      state = chosen.target ?? state;
      if (chosen.assign) ctx = { ...ctx, ...chosen.assign(ctx, payload) };
      onTransition?.({ from, event, to: state, context: ctx });
      listeners.forEach((fn) => fn(state, ctx));
      return true;
    },
    subscribe: (fn) => listeners.push(fn),
  };
}

const fetchMachine = (log) =>
  createMachine({
    initial: 'idle',
    context: { retries: 0, data: null, error: null },
    onTransition: log,
    states: {
      idle: { on: { FETCH: { target: 'loading' } } },
      loading: {
        on: {
          RESOLVE: { target: 'success', assign: (_, data) => ({ data, error: null }) },
          REJECT: { target: 'error', assign: (c, error) => ({ error, retries: c.retries + 1 }) },
        },
      },
      success: { on: { FETCH: { target: 'loading' }, RESET: { target: 'idle', assign: () => ({ data: null, retries: 0 }) } } },
      error: {
        on: {
          RETRY: [
            { target: 'loading', guard: (c) => c.retries < 3 },
          ],
          RESET: { target: 'idle', assign: () => ({ data: null, error: null, retries: 0 }) },
        },
      },
    },
  });

const show = (event) => {
  if (event.ignored) console.log(`  ignored ${event.ignored} in ${event.state}`);
  else if (event.blocked) console.log(`  blocked ${event.blocked} in ${event.state} (guard failed)`);
  else console.log(`  ${event.from} --${event.event}--> ${event.to}`);
};
const machine = fetchMachine(show);

machine.send('FETCH');
machine.send('FETCH');
machine.send('RESOLVE', { id: 1 });
console.log('data:', JSON.stringify(machine.context.data), '| state:', machine.state);

machine.send('FETCH');
machine.send('REJECT', 'timeout');
for (let i = 0; i < 4; i++) {
  machine.send('RETRY');
  if (machine.state === 'loading') machine.send('REJECT', 'timeout again');
}
console.log('after retries:', machine.state, '| retries:', machine.context.retries, '| RETRY is in the table:', machine.can('RETRY'), '(the guard still blocks it)');
machine.send('RESET');
console.log('reset:', machine.state, JSON.stringify(machine.context));

const flags = { isLoading: true, hasError: true, isSuccess: true };
const combinations = 2 ** Object.keys(flags).length;
console.log('three booleans allow', combinations, 'combinations; the machine has 4 states, one active at a time');

Run with Node.js v24.22.1 as js-196.js; two runs gave identical output. Output: idle --FETCH--> loading ignored FETCH in loading loading --RESOLVE--> success data: {"id":1} | state: success success --FETCH--> loading loading --REJECT--> error error --RETRY--> loading loading --REJECT--> error error --RETRY--> loading loading --REJECT--> error blocked RETRY in error (guard failed) blocked RETRY in error (guard failed) after retries: error | retries: 3 | RETRY is in the table: true (the guard still blocks it) error --RESET--> idle reset: idle {"retries":0,"data":null,"error":null} three booleans allow 8 combinations; the machine has 4 states, one active at a time

Key points

  • One status from a finite set replaces many booleans and removes impossible combinations.
  • Transitions are a table of state, event, and next state; unknown events are ignored or flagged.
  • Guards control when a transition may happen; context carries the data.
  • Keep the transition pure and run effects separately; make it testable.
  • Use a machine when several flags depend on each other, not for simple toggles.

Common mistakes

  • Using several booleans that can contradict each other.
  • Allowing events in states where they make no sense, such as a second submit while loading.
  • Mixing side effects into the transition logic, which makes tests hard.
  • Using a machine for a simple toggle.

Follow-ups

  • How would you add a delayed transition for an automatic retry?
  • What is the difference between a state machine and a reducer?
  • What are parallel and hierarchical states?

Tips

  • Start with the invalid combinations of booleans.
  • Draw states and events before coding.
  • Mention guards, context, and where effects run.