DEV Community

Cover image for State machine advent: Visualize your state machines with diagrams as you code (4/24)
Mikey Stengel
Mikey Stengel

Posted on • Edited on

State machine advent: Visualize your state machines with diagrams as you code (4/24)

Yesterday, we wrote our very first state machine in XState.

const lightSwitchMachine = Machine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: {
      on: {
        TOGGLE: 'active'
      }
    },
    active: {
      on: {
        TOGGLE: 'inactive'
      }
    },
  }
});
Enter fullscreen mode Exit fullscreen mode

Just like any other code, reasoning about it once its written can be difficult especially as the complexity of our machines will increase. Here is where one of the unique traits of state machines come into play. Because we have modeled every possible state and their transitions in a centralized JSON object, and the fact that XState is compatible with a protocol called SCXML (short for statechart XML), we can copy the exact state machine from above into a visualizer which will turn our code into a nice looking graph.

https://xstate.js.org/viz/?gist=05c0640a118c35aa236bccc506d2b243

The visualizer works amazingly well and is a very interactive tool. You can click on the toggle button which will send a toggle event to your machine. Observe how the machine will transition from the inactive to the active state afterward.

By using the visualizer, we can now reason about our code more easily, share the diagram with our coworkers which can be super helpful when communicating with non-technical people and visualize changes to our state machine by editing the machine directly within the visualizer.

Looking at the graph is a great way to determine bugs in your state machine logic (such as missing transitions) that you wouldn't even notice by solely looking at your code.

About this series

Throughout the first 24 days of December, I'll publish a small blog post each day teaching you about the ins and outs of state machines and statecharts.

The first couple of days will be spent on the fundamentals before we'll progress to more advanced concepts.

Top comments (2)

Collapse
 
davidkpiano profile image
David K. 🎹

Great series, keep it up!

Collapse
 
codingdive profile image
Mikey Stengel

Thank you David. This really means a lot to me :)