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 statestype ToggleState = "off" | "on";
// Define eventstype ToggleEvent = { type: "TOGGLE" };
// Create machineconst toggleMachine = createMachine<ToggleState, ToggleEvent>({ id: "toggle", initial: "off", states: { off: { on: { TOGGLE: "on", }, }, on: { on: { TOGGLE: "off", }, }, },});
// Usagelet 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
-
Define TypeScript types - Create union types for states (
'off' | 'on') and events ({ type: 'TOGGLE' }) to get type safety throughout your application. -
Create machine with initial state - Use
createMachinewith aninitialproperty to specify which state the machine starts in. -
Define state transitions - In the
statesconfig, each state has anonobject mapping event types to target states. -
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
- Traffic Light Example - See how to handle multiple states with cyclic transitions
- Form Validation Example - Learn about guards and conditional transitions
- API Documentation - Explore the complete API reference