Creating Your First Machine with createMachine
What you'll learn: How to define a state machine in XState using createMachine and its configuration object syntax.
Now that you understand XState's core concepts—states, events, and transitions—it's time to actually build one. XState provides the createMachine function to define machines using a configuration object that describes all possible states and how they transition.
The Basic Structure
Think of createMachine as drawing a map of your component's behavior. You provide an object that specifies:
- An
idfor debugging - The
initialstate where the machine starts - A
statesobject containing every possible state - Inside each state, an
onobject mapping events to target states
A Simple Toggle Machine
Here's a basic toggle machine—like a light switch:
import { createMachine } from 'xstate';
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: {
on: {
TOGGLE: 'active'
}
},
active: {
on: {
TOGGLE: 'inactive'
}
}
}
});
This configuration says: "Start in inactive. When a TOGGLE event arrives, move to active. From active, TOGGLE returns to inactive."
Reading the Configuration
The nested structure mirrors how you think: "When I'm in this state and this event happens, go to that state." No manual boolean flipping, no if/else chains—just a declarative map of behavior.
The machine definition is pure—just a configuration object. Later lessons will show you how to interpret and use it in React components.
Key Takeaway: createMachine takes a configuration object describing states and transitions, creating a declarative, visual map of your component's behavior that's easy to reason about and modify.