This example demonstrates the most basic state machine: a toggle that switches between two 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 toggle machine has two states:- inactive - The initial state
- active - The toggled state
toggle event transitions between these states.
Machine Definition
Here’s the complete toggle machine:Implementation
import { createActor } from 'xstate';
import { toggleMachine } from './toggleMachine';
const toggleActor = createActor(toggleMachine);
toggleActor.subscribe((snapshot) => {
outputEl.innerHTML = snapshot.value === 'active' ? 'Active' : 'Inactive';
});
Complete Example
Key Concepts
- States: The machine can only be in one state at a time (
inactiveoractive) - Events: The
toggleevent triggers state transitions - Actor: The running instance of the machine that maintains state
- Snapshot: The current state returned by
subscribe()