Use a Recoil Atom to Share State Between Two React Components

Tomasz Łakomy
InstructorTomasz Łakomy

Share this video with your friends

Send Tweet
Published a year ago
Updated 3 months ago

Recoil is a brand new state management library for React developed by Facebook.

In this quick lesson we're going to learn how to add it to a React app and how to use a Recoil atom in order to share state between two React components using useRecoilState hook

Tomasz Łakomy: [0:00] We have a brand-new React project and we would like to add Recoil to it. Recoil is a state management library for React, which was created by Facebook team.

[0:08] First up, open up the terminal and run yarn add recoil. Of course, you can use npm as well. It's fine. After it's successfully installed, close the terminal and I'm going to import {RecoilRoot} from "recoil". All the components that are going to use the Recoil state need this RecoilRoot component to appear somewhere in the parent tree.

[0:29] What I'm going to do is that I'm going to wrap our entire app in the RecoilRoot component. Let me just go over here and do that quickly. Save.

[0:37] Now, we can create our very first atom. In recall, atom represents a piece of state. First up, let me import {atom} from "recoil". Next, create an atom for our counter component. I'm going to do const numState = atom().

[0:51] Atom takes an object with two feats that are necessary. First up is the key, which has to be unique. I'm just going to call it numState. Secondly, there's the default value, which I'm going to set to .

[1:01] Next, I'm going to create a Counter component. For now, it's just going to render a button with a value of . Let me add it over here. To use our atom in our Counter component, we have to import {useRecoilState} from "recoil".

[1:14] In our Counter component, I'm going to destructure number and setNumber from useRecoilState(numState). Let me save that. In order to use the RecoilState, we have to pass in the atom. Right now, if I take this number and use it over here, we can see that this value is still .

[1:30] If I do onClick =, and I'm going to pass in a function which is going to set the number to number + 1, we can see that if I click on the button, the Counter state is going to be updated. The best part of having atoms is that we can use the same state in multiple components.

[1:46] If I create a new function, which I'm going call Display(), and this function is going to return a <div> with a number, I can do exactly the same thing that we did over here. Let me copy that and paste it. Since we are not going to use the set number, I am not going to destructure that.

[2:02] If we save that and use this Display component over here, Display, we can see that if I click on the button, both of those components are going to be updated. The reason why it happens is that both of them are using the same atom in order to keep track of their numState.