Isolate State in an Application with Jotai Provider

Daishi Kato
InstructorDaishi Kato
Share this video with your friends

Social Share Links

Send Tweet

Now that we have a lot of functionality finished for this example, we'd like to create multiple components (or multiple canvases) that you can draw on.

You'll notice that if you do that right now, drawing on one will draw on the other because state is global to the entire application.

Jotai exposes a Provider component that allows you to wrap any part of your application that you want to isolate state to.

Instructor: [0:00] At first, we modify SvgRoot.tsx. Previously, the most point was from the absolute coordinates of the screen. We would like to make it relative in the canvas, subtract x and y of getBoundingRect, and reduce the height of the canvas to make it a little smaller. Now, we are ready.

[0:27] Open app.tsx and copy SvgRoot and Controls component. This creates a new canvas, which is identical to the first one. If you draw a shape in my canvas, the same shape is drawing another canvas. This is expected behavior as we have one global state.

[0:51] We can make them two separate canvases easily. Jotai exposes Provider. It's like context Provider component, and under the hood it uses context. In the Provider component tree, global state is isolated.

[1:09] Now, we can draw something on one canvas and the other canvas is not affected. This means our atoms are not single terms. What we built with the atom function is called atom configs, and they don't hold values. Provider has a store which holds atom values.

[1:29] Let's try using a single Provider instead of two. This makes both canvases share the same atom values. Even if we remove the Provider completely, it still works in Providerless mode. It's using a default store.

[1:45] Provider has some other features like passing initial values in props. Unless you need Provider, the Providerless mode just works for you.