3 easy steps to use xstate visualizer in Next.js

Cover Image for 3 easy steps to use xstate visualizer in Next.js
Ali Bentaleb
Ali Bentaleb
Xstate visualizer is a great tool to get a broad glimpse of what your xstate machine looks like.

In this tutorial, we are going to focus on how to visualize your xstate machines in Next.js project

Step 1: install XState VSCode extension

To install it, navigate to your Next.js project home directory, and type in this command

code --install-extension statelyai.stately-vscode

This will install vscode state visualizer in your vscode editor.

If you have not created your Next.js project you can either visit my link to create it, or Next.js official documentation in this link

Make sure also to install xstate and @xstate/react using
npm i xstate @xstate/react

##yarn
yarn add xstate @xstate/react
## Step 2: Create your state machine

Next, we will create our state machine,

Create machine folder, and then create a file engine.js

import { createMachine, interpret } from 'xstate';



const engineMachine = createMachine({
  id: 'Engine',
  initial: 'idle',
  states: {
    idle: { on: { REV: 'active' } },
    active: { on: { BRAKE: 'idle' } }
  }
});



const engineService = interpret(engineMachine)
  .onTransition((state) => console.log(state.value))
  .start();
// => 'inactive'

toggleService.send('BRAKE');
// => 'active'


toggleService.send('REV');
// => 'idle'

This will create an engine machine, with an idle initial state.

If we pass in transition REV in state idle, we will be in state active

If we pass in transition BRAKE in state active, we will be in state idle.

Step 3 : visualize the state machine

Now , open engine.js file, and you will be able to see a gray hypertext right on top of createMachine (it is highlighted with yellow in the image below).

Click on it and you may be able to visualize your xstate machine.

xstate visualizer for state machine in a next.js project

Conclusion

We have seen how to install stately-vscode plugin in order to visualize xstate state transition diagram in visual studio code which enhance our understanding of the state machine of our system

If you love working with Next.js here is a link to browse Next.js topics like tables, loading spinners, charts

How to useContext to share Rea...What is Next.js