What are state machines?
A finite state machine is a mathematical model of computation that describes the behavior of a system that can be in exactly one of a finite number of states at any given time. The machine can change from one state to another in response to events; this change is called a transition.Why use state machines?
Statecharts are a formalism for modeling stateful, reactive systems. This is useful for declaratively describing the behavior of your application, from individual components to overall application logic.XState is based on the SCXML specification, which is a W3C standard for representing state machines in XML.
Basic state machine
Here’s a simple traffic light state machine:Key concepts
States
States represent the different modes or conditions your system can be in. In the traffic light example, the states aregreen, yellow, and red.
Events
Events trigger transitions between states. Events are objects with atype property. In the example above, the TIMER event triggers transitions.
Transitions
Transitions define how the machine moves from one state to another in response to events. They are defined in theon property of each state.
Initial state
The initial state is the state the machine starts in. It’s defined with theinitial property.
Statecharts vs state machines
Statecharts extend traditional finite state machines with:- Hierarchical states - States can contain other states
- Parallel states - Multiple states can be active simultaneously
- History states - Remember and restore previous states
- Guards - Conditional transitions
- Actions - Side effects on transitions
Benefits
Predictable behavior
State machines eliminate impossible states and ensure valid transitions
Visual representation
State machines can be visualized, making complex logic easier to understand
Type-safe
TypeScript integration provides compile-time type safety for states and events
Testable
State machines are easy to test - verify all possible states and transitions
Learn more
- Statecharts - A Visual Formalism for Complex Systems by David Harel
- The World of Statecharts by Erik Mogensen
- Watch: Infinitely better UIs with finite automata
Next steps
Actors
Learn about the actor model in XState
States
Deep dive into states and state values
Transitions
Understand state transitions
Quick start
Build your first state machine