Share State Between React Components with Jotai useAtom

Daishi Kato
InstructorDaishi Kato

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

Jotai is a state management library for React. You will learn how it can be used instead of useState for shared state.

We'll start with two Counter components that each have their own React useState instance which isolates the state to that component. To share state, we'll create an atom from jotai and replace the useState calls to useAtom, and that's it, you have shared state.

Lecturer: [0:00] This is a small app with two components that have two individual counts. As they're individual, clicking one of the buttons only changes one count. This is because we used two useState hooks in two components. Now, we'd like to convert this app with one shared count.

[0:21] First, let's import Jotai. We import { atom, useAtom}. Atom is a function to create atom configs, and useAtom is a hook to use them. Let's define an atom config. We name it countAtom and pass default value .

[0:40] The atom can be used like state. We replace useState with useAtom and pass the defined atom config. Doing the same for the second component, and that's it. We get a shared count. If we click one button, it counts up both numbers. This works as both useAtom hooks refer the same atom config.

[1:04] Let's try creating another atom. Use the second one for the second component. This behaves like we have two separate useState hooks. The name of atom is not important. For example, we can put the first atom to the second one, and this makes a shared count. Clicking one of the buttons increases both counts.