This example demonstrates a classic finite state machine pattern: a traffic light that cycles through states.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/statelyai/xstate/llms.txt
Use this file to discover all available pages before exploring further.
Overview
The traffic light machine models a signal that transitions through three states:- green - Go
- yellow - Caution
- red - Stop
TIMER event advances to the next state in the cycle.
Machine Definition
Implementation
initial: 'green',
states: {
green: { on: { TIMER: 'yellow' } },
yellow: { on: { TIMER: 'red' } },
red: { on: { TIMER: 'green' } }
}
const actor = createActor(lightMachine);
actor.subscribe((state) => {
console.log(state.value);
});
actor.start();
// logs 'green'
Complete Example
Adding Delays
You can make the transitions automatic usingafter:
Key Concepts
- Sequential transitions: States transition in a defined order
- Cyclic behavior: The last state transitions back to the first
- Single event type: One event (
TIMER) drives all transitions - Deterministic: Always in exactly one state at a time
Use Cases
This pattern works well for:- Wizards and multi-step forms
- Onboarding flows
- Game turn systems
- Process workflows
- Animation sequences