Share State Between React Components with Jotai useAtom

Daishi Kato
InstructorDaishi Kato
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 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.

egghead
egghead
~ 17 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today