Skip to main content
This example demonstrates the most basic state machine: a toggle that switches between two states.

Overview

The toggle machine has two states:
  • inactive - The initial state
  • active - The toggled state
A toggle event transitions between these states.

Machine Definition

Here’s the complete toggle machine:
import { createMachine } from 'xstate';

export const toggleMachine = createMachine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: {
      on: {
        toggle: 'active'
      }
    },
    active: {
      on: {
        toggle: 'inactive'
      }
    }
  }
});

Implementation

1
Create the machine
2
Define a machine with two states and a toggle transition between them.
3
Create an actor
4
Instantiate the machine logic with createActor():
5
import { createActor } from 'xstate';
import { toggleMachine } from './toggleMachine';

const toggleActor = createActor(toggleMachine);
6
Subscribe to state changes
7
Listen for state updates to render the UI:
8
toggleActor.subscribe((snapshot) => {
  outputEl.innerHTML = snapshot.value === 'active' ? 'Active' : 'Inactive';
});
9
Start the actor
10
Begin execution:
11
toggleActor.start();
12
Send events
13
Trigger transitions by sending events:
14
toggleButton.addEventListener('click', () => {
  toggleActor.send({ type: 'toggle' });
});

Complete Example

import { toggleMachine } from './toggleMachine';
import { createActor } from 'xstate';

const toggleActor = createActor(toggleMachine);

const toggleButton = document.querySelector<HTMLButtonElement>('#toggle')!;
const outputEl = document.querySelector<HTMLDivElement>('#output')!;

toggleActor.subscribe((snapshot) => {
  outputEl.innerHTML = snapshot.value === 'active' ? 'Active' : 'Inactive';
});

toggleActor.start();

toggleButton?.addEventListener('click', () => {
  toggleActor.send({ type: 'toggle' });
});

Key Concepts

  • States: The machine can only be in one state at a time (inactive or active)
  • Events: The toggle event triggers state transitions
  • Actor: The running instance of the machine that maintains state
  • Snapshot: The current state returned by subscribe()