State machines for the rescue

| 2 min read

Most of the features we are creating in our applications can be described in finite state machines. When we think about web applications we are thinking about the state in which our application is. Then we have ways we can go and modify the state of the application.

The login page is a great example. When you enter valid credentials, you were transitioned from the “not logged in” state into the “logged in”. Let’s see how knowledge about that can help us create more predictable and less error-prone applications.


What exactly are finite state machines?

Sample finite state machine chart

Definition of this you can read on Wikipedia page. There you can find more information about how they are defined and what they really are. But to make a long story short. Your application has a current state. You can transition to other states that are available in the current state. When transition you preserve metadata why this transition happens, eg. request is rejected or resolved.

Let’s see it in action:

What is XState?

XState is a library to create the finite state machine for JavaScript. It can help you describe states and available transitions in your application. It can be used in plain JavaScript but also has first-class support for the most popular frontend frameworks.

Why XState?

It can help you describe the behavior of your application. You can restrict access to the events in a certain state. It’s easy to use and straightforward.

When we want to create a toggle, for example when we are showing the user a popover.

import { createMachine } from 'xstate';

createMachine({
id: 'popover-toggle',
initial: 'inactive',
states: {
inactive: { on: { TOGGLE: 'active' } },
active: { on: { TOGGLE: 'inactive' } }
}
})

We need to define at least 3 fields:

  • id — identifier of the state machine among others, should be unique
  • initial — initial state which will be your state machine, should be one of the defined states
  • states — available states in which your machine can be your machine

We must be creating one small piece of application state instead of the whole application component. This state machine works only for popover, not for modals, or others components on your site. Keep it on the same level as a component that is for.

Summary

XState can help you with managing requests, keep states of modal, popovers, or other components in your application. Smooth transition to available state and visualizer helps you build better, more predictable, and less error-prone applications. Check more in XState docs on how to use finite state machines.