← Back to React, page 8

react-0143 · Hard senior

Why use a state machine (useReducer or XState) for complex UI flows, and how does it prevent impossible states?

A state machine lists the states a flow can be in and the events allowed in each state. Booleans such as isLoading, isError and isSuccess can combine into impossible states (loading and error at once). A single status field with a reducer that checks the current state before applying an event makes invalid transitions impossible and logic easy to test. useReducer is enough for small flows. XState adds visualisation, guards, delayed transitions and actors for larger ones.

Full answer

Complex flows (checkout, wizards, upload, authentication, form submission with retry) often start with several booleans. With isLoading, isError and data, there are eight combinations, and many of them make no sense. Bugs appear when one flag is updated and another is forgotten.

A state machine fixes this with a model:

  • A finite set of states (idle, loading, success, error).
  • A set of events (SUBMIT, RESOLVE, REJECT, RETRY).
  • Transitions: for each state, which events are allowed and which state they lead to. Events that are not defined in a state are ignored.
  • Optional context data (the result or the error message) stored with the state.

Benefits. Impossible states cannot be represented. The behaviour is explicit and reviewable, and even a non-programmer can read the diagram. Testing becomes a matter of feeding events and checking states. Side effects (requests, timers) are triggered by transitions or by effects that react to the state, not by scattered handlers.

In React. useReducer with a status discriminated union and a switch on state.status is a lightweight machine. TypeScript helps by making each state carry only its relevant data. For larger flows, XState (createMachine, useMachine) adds guards (conditions), delayed transitions, parallel and nested states, actors for invoked work, and visual tools. Redux Toolkit's createSlice can be used in a similar way.

When not to use it. A simple toggle or a one-field form does not need it. The model pays off when there are more than two or three states, retries, cancellation or time-based transitions.

The example is a small submit flow where a duplicate SUBMIT during loading is ignored by design.

tsx
import { useReducer } from 'react';

type State =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; message: string }
  | { status: 'error'; error: string };

type Event = { type: 'SUBMIT' } | { type: 'RESOLVE'; message: string } | { type: 'REJECT'; error: string } | { type: 'RETRY' };

function reducer(state: State, event: Event): State {
  switch (state.status) {
    case 'idle':
      return event.type === 'SUBMIT' ? { status: 'loading' } : state;
    case 'loading':
      if (event.type === 'RESOLVE') return { status: 'success', message: event.message };
      if (event.type === 'REJECT') return { status: 'error', error: event.error };
      return state;
    case 'error':
      return event.type === 'RETRY' ? { status: 'loading' } : state;
    default:
      return state;
  }
}

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

  return (
    <div>
      <p>Status: {state.status}</p>
      <button onClick={() => dispatch({ type: 'SUBMIT' })}>Submit</button>
      <button onClick={() => dispatch({ type: 'REJECT', error: 'Network down' })}>Fail</button>
      <button onClick={() => dispatch({ type: 'RETRY' })}>Retry</button>
      <button onClick={() => dispatch({ type: 'RESOLVE', message: 'Saved' })}>Succeed</button>
      {state.status === 'error' && <p role="alert">{state.error}</p>}
      {state.status === 'success' && <p>{state.message}</p>}
    </div>
  );
}

The check pressed the buttons in order: Submit, Fail, Retry, Succeed. Retry is only valid in the error state, and Fail only in loading, so the flow ended in success after going through loading twice. Rendered result: <div><p>Status: success</p><button>Submit</button><button>Fail</button><button>Retry</button><button>Succeed</button><p>Saved</p></div>

Key points

  • Multiple booleans allow impossible states. A single status makes them unrepresentable.
  • A machine defines states, events and which transitions are allowed in each state.
  • Events that are not valid in the current state are ignored, so double submits are harmless.
  • useReducer covers small flows, and XState adds guards, delays, nesting and tooling.
  • Do not use it for trivial state.

Common mistakes

  • Modelling a flow with independent booleans.
  • Allowing every event in every state and handling conflicts with ad hoc checks.
  • Storing derived flags such as isLoading next to status.
  • Starting requests inside the reducer.
  • Using a full machine library for a two-state toggle.

Follow-ups

  • How does a discriminated union help TypeScript users here?
  • How would you add a cancel event and a timeout in XState?
  • Where do side effects live in a machine-based design?

Tips

  • Start with the impossible-states example.
  • Draw the states and events, even for a simple case.
  • Say when it is overkill.