Configure recoil.js to your React project

React State Management with Recoil

Chintan Sudani
Bitontree
3 min readJan 1, 2021

--

What is recoil.js to React?

recoil.js is the state management library for React. Hence it can be used instead of usestate in your React Project.

How are they different from each other?

  • It seems like React ( global version of useState)
  • You can manage your state very easily.
  • It has very simple concepts like atom and selector.
  • Very clean and simple working model.

Installation:

  • for npm package: npm install recoil
  • for yarn package: yarn add recoil

Implementing State

So basically there are two concepts introduced in Recoil i.e. atom and selectors.

Atom:

An atom represents a piece of state. Atoms can be understood as something that can be read from and written to from any component.
Components that are associated with this atom will automatically be re-rendered once the atom is updated.

Selectors:

A selector represents a piece of derived state. You can think of this as the output of passing state to a function that modifies the given state in some way.

Using State:

There are two ways to get the declared state into our components. i.e. by useRecoilState or useSetRecoilState, useRecoilValue.

useRecoilValue:

Whenever you want to use the value of the state but don’t want to update it in the whole component.

useRecoilState:

Whenever you want to use the value of the state and also want to update it globally through the component itself.

useSetRecoilState:

Returns a setter function that can be used asynchronously to change the state. The setter may either be passed a new value or an updater function that receives the previous value as an argument.

Conclusion:

We have successfully implemented the global state using Recoil. Although this was a small part, it is enough to use it in your projects. It is a developing project with many changes being present explicitly in syntax or under the hood. So I wouldn’t really suggest using it in big projects. One can always try new things and in my opinion, if you like Hooks then you would love using Recoil.

References:

--

--