Skip to content

How to understand a XState codebase

XState models behaviour as state machines and statecharts. A machine lists every state, the events each state accepts and what happens on each transition. Once you find the machine definition, you have a precise map of a feature's behaviour.

How to tell it's XState

  • xstate and often @xstate/react in package.json
  • setup({...}).createMachine({...}) or createMachine({...})
  • useMachine, useActor or createActor calls

Where things usually live

src/machines/
Machine definitions.
src/machines/*.actions.ts
Implementations of named actions, guards and actors, if split out.
components using useMachine
Where events are sent and state is displayed.

Conventions, not rules. Real projects rename and move things, so confirm against the repository.

Where to start reading

  1. The machine definition: initial, states and the on maps
  2. The setup implementations behind each named action and guard

How a request moves through the code

  1. 1A component starts the machine with useMachine or createActor.
  2. 2The UI sends an event, such as { type: 'SUBMIT' }.
  3. 3The current state looks up the transition for that event, checking guards.
  4. 4Actions run, context updates, and the machine enters the new state.
  5. 5Invoked actors (promises, callbacks, child machines) run while in a state and send events back.

Questions to ask about the repository

  • Describe every state and transition in this machine.
  • Which events are ignored in each state?
  • What do the invoked actors do, and how do they report back?

What trips people up

  • XState v4 and v5 differ in APIs (interpret versus createActor, services versus actors).
  • Events sent in a state with no matching transition are dropped silently.