What Are Finite State Machines?

Learn about how XState incorporates finite state machines, statecharts, and actor models for efficient global state management in applications.

If we were to guess what finite state machines are, we would probably say they are related to managing state in applications. After all, this whole chapter is on that topic!

Finite state machines have nothing to do with applications; they have nothing to do with React or even programming at all. A finite state machine is a mathematical model of computation. It’s an abstract concept that can be applied to real-life objects or problems, and it represents a machine that can be in exactly one of a finite number of states at any given time. The predefined states can be changed from one to another in response to some user input.

Let’s look at some of the common examples of state machines:

  • Traffic lights: A traffic light can be green, red, or yellow at any time, and it should never display two colors at once.

  • Elevator: The default state of an elevator is to stand still with the doors closed. When a user pushes the button summoning the elevator, the elevator transitions to a state of movement. When it reaches the right floor, it opens and then closes its doors. The elevator then goes back to the default, idle state, waiting for the next user input.

It’s time to find out why we are talking about this concept at all. Any guesses? Finite state machines are the basic concept of the state management library we’re analyzing in this chapter: XState.

What is XState—high-level concepts

Now that we have a grasp on the theoretical concept of finite state machines, we can move on to talking about XState and its main concept: finite state machines! But this time, we’ll look at it in the world of programming global state in applications.

When using XState to manage global state in an application, we should think of our state as a finite state machine. This means abandoning the previous concept of representing state as a plain JavaScript object. With XState, a component—or a surface—is a machine that can be in one of multiple predefined states.

Let’s consider the user login flow. Our entire app can be in one of two states:

  • The user is logged in

  • The user is not logged in

We would also need a transition mechanism for the user to move from one of the states to the other. The same goes for images on the home surface. Every image is either in the state of being liked or not liked. The user can change the current state of the image by clicking the heart icon below the image.

Besides finite state machines, there are two other important concepts used in XState:

  • Statecharts

  • Actor model

Statecharts

Statecharts are basically drawings that can be used to represent state machines. Here’s an example of a statechart representing the state and transitions of a light bulb:

Get hands-on with 1200+ tech skills courses.