Introduction to Xstate
From the docs:
XState is a library for creating, interpreting, and executing finite state machines and statecharts, as well as managing invocations of those machines as actors.
uh?! 🤔
What is a finite state machine?
A finite state machine describes the behavior of a system that can be in only one state at any given time (i.e awake or asleep )
Formally, finite-state machines have five parts:
- A finite number of states
- A finite number of events
- An initial state
- A transition function that determines the next state given the current state and event
- A (possibly empty) set of final states
If you want to read more about finite state machines, I found this article to be the simplest for describing finite state machines.
What are Statecharts/State Transition diagrams?
A statechart or a state transition diagram is a diagram that explains the transition between states.
What does it mean “managing invocations of those machines as actors”?
An actor in XState is simply a machine that communicates with other machines, which means that you invoke a message between 2 or more machines.
Get Liron Burrack’s stories in your inbox
Join Medium for free to get updates from this writer.
From this article:
When an actor receives a message, it can do one of these 3 things:
- Create more actors
- Send messages to other actors
- Designate what to do with the next message
Xstate code
Let's see a coding example that represents our dog's state (awake, asleep) by creating a machine:
import { createMachine } from 'xstate';
const promiseMachine = createMachine({
id: 'dog',
initial: 'awake',
states: {
awake: {
on: {
FALLS_ASLEEP: { target: 'asleep' },
}
},
asleep: {
on: {
WAKES_UP: { target: 'awake' }
}
},
}
});Our statechart using the XState Visualizer tool:
Code + visualizer can be found here.







