Skip to content

Basic State Machine

Learn how to create a simple state machine with two states.

Use Case

This example demonstrates a toggle switch or on/off button - the foundation for understanding state transitions in XMachines. It’s the simplest possible state machine with just two states and one event type.

Complete Code

import { createMachine } from "xstate";
// Define states
type ToggleState = "off" | "on";
// Define events
type ToggleEvent = { type: "TOGGLE" };
// Create machine
const toggleMachine = createMachine<ToggleState, ToggleEvent>({
id: "toggle",
initial: "off",
states: {
off: {
on: {
TOGGLE: "on",
},
},
on: {
on: {
TOGGLE: "off",
},
},
},
});
// Usage
let state = toggleMachine.initialState;
console.log(state); // 'off'
state = toggleMachine.transition(state, { type: "TOGGLE" });
console.log(state); // 'on'
state = toggleMachine.transition(state, { type: "TOGGLE" });
console.log(state); // 'off'

Code Explanation

  1. Define TypeScript types - Create union types for states ('off' | 'on') and events ({ type: 'TOGGLE' }) to get type safety throughout your application.

  2. Create machine with initial state - Use createMachine with an initial property to specify which state the machine starts in.

  3. Define state transitions - In the states config, each state has an on object mapping event types to target states.

  4. Use the machine - Call transition(currentState, event) to compute the next state based on the current state and incoming event.

Key Concepts

  • State: The current mode or condition of the machine ('off' or 'on')
  • Event: A trigger that causes a state change ({ type: 'TOGGLE' })
  • Transition: A rule defining how the machine moves from one state to another
  • Type Safety: TypeScript ensures you only use valid states and events, catching errors at compile time

Next Steps