State Machines: The Fundamentals
These are my notes from David Khourshid’s course on Frontend Masters, “State Machines In Javascript with XState”
Graph Theory
To understand finite state machines and state charts, we need to understand some basic graph theory.
A graph is a computer science concept that represents the relationships between things. A graph is made up of nodes and edges. The nodes are the “things” and the edges are the relationships between them.
The graph above is an undirected graph because the edges don’t have arrows specifying the direction of the relationships. So the relationships can go both ways between nodes.
Directed graphs are a bit different.
In a directed graph, the edges specify a direction. For example, you can go from A to B, but not from B to A. In this way the edges represent paths. This is similar to how we think about user flows in applications.
So a finite state machine is a directed graph.
A state chart (pictured above) contains the following components:
States
States are distinct, mutually exclusive modes or statuses. (Think “asleep” vs. “awake”).
Transitions
Transitions represent a directed graph, showing the direction that can be travelled between nodes.
Events
Events are labels on transitions that describe how we can get from one state to another. For example, we can only get from pending to resolved if the resolve event happens.
Initial state
This is what it sounds like. Every state machine has exactly one initial state.
Final states
Once these states are reached, the state machine can no longer accept any events or transition to any other states.