How to use React-Recoil’s Atom

Yaniv Beaudoin
3 min readSep 25, 2020

--

React recoil is aspiring to be the next big state management library for React. As of September 2020, it is still under the experimental stage but already has more than 9.5k starts. It is supposed to smoothly integrate with react’s newest features while allowing advanced state management. This article discusses the concept called atom which is the first concept you should learn when starting to use react-recoil.

Share State Between Components

An atom in react-recoil is a piece of state that we can share between components. To define an atom we need a unique key and a default value. After the definition, we can use this atom to share state in every component we want across our app.

const circleColorState = atom({
key: "circleColor",
default: 'blue'
})

To use the value of the atom we will use the useRecoilState hook and to set the value we will use the useSetRecoilState hook. The component that uses useRecoilState will re-render every time the atom state changes.

Although the example above is very simple, it explains the concepts of an atom very nicely. We define it independently of the react rendering tree and then connect it where it is needed. Just throw in an atom and that’s it. ColoredCircle and ColorChangingButton are not aware of each other, yet they can share state. Nothing too fancy but very useful. Even if you don’t use the more advanced features, this simple feature is already very useful.

If you want to share a state between components then just throw in an atom

Atom Family

The Atom family function enables us to use the same atom to manage different states with the same behavior.

const circleColorState = atomFamily({
key: "circleColor",
default: 'blue'
})

With just a few changes to the previous example, we can use atoms to manage three different states:

  • Line 4: Calling atomFamliy instead of atom
  • Line 10 and 18: Adding id when calling to circleColorState.
  • Lines 28–33: Passing the same id to ColorChangingButton and ColoredCircle so they will both use the same atom.

Here is the result:

Conclusion

React-recoil’s atom offers a clean API to share pieces of state across react components. This simple API allows us to build independent sharable pieces of state without having to think of the big picture every time we need to share state between components. When you need to share state between components, just throw in an atom. Of course, there is a lot more to know about the atom API and a lot more about react-recoil but, understanding what is an atom already gives you useful functionality.

Looking for a job?

Checkout my latest project: secrethunter.io

--

--

Yaniv Beaudoin
Yaniv Beaudoin

Responses (1)