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.

Screen Shot 2021-03-17 at 1.07.38 PM.png

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.

Screen Shot 2021-03-17 at 1.08.27 PM.png

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.

Screen Shot 2021-03-17 at 1.10.25 PM.png

A state chart (pictured above) contains the following components:

States

States are distinct, mutually exclusive modes or statuses. (Think “asleep” vs. “awake”).

Screen Shot 2021-03-17 at 1.11.40 PM.png

Transitions

Transitions represent a directed graph, showing the direction that can be travelled between nodes.

Screen Shot 2021-03-17 at 1.12.54 PM.png

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.

Screen Shot 2021-03-17 at 1.16.06 PM.png

Initial state

This is what it sounds like. Every state machine has exactly one initial state.

Screen Shot 2021-03-17 at 1.17.11 PM.png

Final states

Once these states are reached, the state machine can no longer accept any events or transition to any other states.

Screen Shot 2021-03-17 at 1.37.20 PM.png