Share and Isolate XState State using Jotai Provider

Daishi Kato
InstructorDaishi Kato
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

When you reuse a component, there are times when you’d like that state to share the same values as other instances of that state. In other cases, you want to isolate your state. With Jotai, you only need to wrap your components that you want to share state in Jotai’s <Provider> component the subsequent atom (and XState machine) state is shared for those components.

Daishi Kato: [0:01] We import createMachine from the xstate library and atomWithMachine from the jotai/xstate integration library. Using them, we define lightMachine and lightAtom. It's one of the most minimalistic atoms with State machine. Neither of the lightMachine or the lightAtom hold state values. They are definitions to describe the behaviors.

[0:31] When we use the atom, the library initializes the lightAtom and starts the lightMachine. What's important is that we can instantiate two machines from a single definition.

[0:44] To demonstrate such a use case, let's import Provider from the Jotai library. Provider is a component where atom values exist. Make the app component to have Provider components and light components. We have two Provider components, and each Provider component has two light components in it.

[1:08] The two light components in the same Provider component share the same admin values. On the other hand, light components in another Provider component are isolated and they share different admin values.

[1:24] Let's see how this behaves. There are four circles shown. The two circles above come from the same Provider. If you click one of those, both will change. The same applies to the other two circles. This is because we have two Providers, and they have own admin values separately. Note that we have just one machine in our code. With one machine defined, we can create multiple state values.

[2:00] Same for atoms. We define a single atom which can be used for multiple state values. Providers are the method to separate the values. Jotai atoms and XState machine are pretty similar in terms of the state obstruction.