This guide will walk you through creating your first state machine with XState. You’ll learn how to define states, handle events, and manage context.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.
Prerequisites
Make sure you have XState installed:Build a toggle machine
Let’s create a simple toggle machine that switches between inactive and active states, and counts how many times it’s been activated.Import XState functions
First, import the functions you’ll need from XState:
createMachine- Creates a state machine definitioncreateActor- Creates a running instance of the machineassign- Updates the machine’s context (data)
Define the state machine
Create a state machine with two states and a counter:This machine:
- Starts in the
inactivestate - Has a
countin its context that tracks activations - Transitions to
activewhen it receives aTOGGLEevent - Increments the counter each time it enters the
activestate - Returns to
inactivewhen it receives anotherTOGGLEevent
Create an actor
An actor is a running instance of your state machine logic, like a store:The actor hasn’t started yet, so it won’t process events until you start it.
Subscribe to state changes
Subscribe to the actor to receive updates when the state changes:The
state object contains:state.value- The current state namestate.context- The current context data
Start the actor
Start the actor to begin processing:When you start the actor, it immediately emits its initial state.
Complete example
Here’s the complete code:Understanding the core concepts
States
States represent the different modes your application can be in. In this example:inactive- The toggle is offactive- The toggle is on
Events
Events trigger transitions between states. Events are objects with atype property:
Context
Context is the data that persists across state transitions. Useassign to update context:
Actors
Actors are running instances of your state machine logic. They:- Process events
- Emit state changes
- Can be subscribed to for updates
- Can spawn other actors
Next steps
Core concepts
Dive deeper into state machines and actors
Hierarchical states
Learn about hierarchical and parallel states
Actions
Execute side effects in your state machines
Stately Studio
Visualize and edit your state machines