Jotai has a primitive and flexible API, because of this it's up to you on how you manage your state within an atom.
Sometimes your state is complex enough to warrant a sophisticated library for safer abstraction. This is where you can install xstate to your application and Jotai will work seamlessly with the state machines that you define using atomWithMachine
.
This allows you to consume the machine like any other atom in your components with useAtom
.
As an added bonus, I'll show you how to use xstate's visualizer to develop and interact with your state machine in dev tools.
Instructor: [0:02] CreateMachine is one of the APIs exported from the XState library. Using createMachine we define a very small machine called lightMachine. It has three states -- green, yellow, and red. The initial state is green.
[0:20] We define one event called Next. The next event changes the state. This will be one of the simplest machines. We create an atom using the define machine.
[0:36] Let's use atomWithMachine, which is exported from jotai/xstate library. We call it Light On and enable the dev tools option. To use the table tools, we need to call inspect function from the @xstate/inspect package. This will look for an iframe with data-xstate attribute, which we defined in the index.html file. We also define some styles to show the dev tools in the bottom half of the view.
[1:11] Now, let's make the light component to use the defined light atom. The light atom can be used as a normal atom, and we use the useAtomHook from the Jotai library. It returns a state variable and the send function. The light component renders an SVG document.
[1:35] Our light machine state is a color value, so we specified the value in the field property. We also show the value in the text element. In handleClick function, we send the next event. This will be invoked when we click the SVG circle.
[1:57] We are all set. Let's see how it works. If you click the circle, the color changes. Look at the dev tools. A statechart of a light machine is represented as a graph. You see three states connected with links having the next event labels.
[2:19] It starts from the green state, goes to yellow, and red, and loops back to green. When you click the circle shape, we will see the active state changes in the statechart. You can even send the next event in the dev tools. You can do so in the events feature or the events folder in the statechart.
[2:46] Changing the state in the dev tools is also synchronized with the app. This is a nice feature with the statechart and it helps to deal with complex states.
[2:59] Let's recap. We created a machine with createMachine. This is a pure XState way. Then, we use atomWithMachine to define atom with the created machine. We can use the atom like a normal atom in Jotai.
[3:19] Changing the state will show up in the dev tools and the changes are in sync in both ways.