6 Concepts you Need to Know to Master Recoil.js State Management

Main concepts and terms you need to know when working with Recoil.js

Picture of Nsikak Imoh, author of Macsika Blog
Abstract background with the text 6 Concepts you Need to Know to Master Recoil.js State Management
Abstract background with the text 6 Concepts you Need to Know to Master Recoil.js State Management

Table of Content

When using a new library or framework, you will encounter new concepts and terms.

These terms and concepts may be similar across different libraries, like the concept of props and components. And sometimes, they can be specific to a particle library.

In this article, we will look at the main concepts and terms you need to know when working with Recoil.js global state management library for React.js as well as frameworks like Next.js.

Read More: What is React Router, Why use it, and How?

List of Core Concepts to Know when Using Recoil.js

Here are the main concepts and terms you need to know when using Recoil.js:

  1. The RecoilRoot component
  2. The useRecoilState hook
  3. The useRecoilValue hook
  4. The useSetRecoilState hook
  5. Atoms
  6. Selectors

What is the RecoilRoot in Recoil.js?

RecoilRoot is the parent component or provider for a React.js application that uses Recoil.js as a global state manager.

You use it to wrap a parent component that has a shared state among multiple child components.

Although it can be used at any parent component with a shared state, a good place to put the RecoilRoot is in your root component:

Example of RecoilRoot in Recoil.js

import React from 'react';
import {  RecoilRoot } from 'recoil';
function App() {
	return (
		<RecoilRoot>
			<ComponentThatUsesRecoil />    
		</RecoilRoot>  
	);
}
Highlighted code sample.

Read More: What is Next.js On-demand Incremental Static Regeneration and How to Use it?

What is the useRecoilState hook?

The useRecoilState hook makes the React.js component to re-render when any changes occur in the requested atom.

It returns a tuple where the first element is the value of the state and the second element is a setter function that will update the value of the given state when called.

Also, know that the setter function may either take a new value as an argument or a function (whose purpose is to update), which receives the previous value as a parameter.

The useRecoilState hook is similar to the React useState() hook, except it takes a recoil state instead of a default value as an argument.

Recoil.js recommends using this hook when a React.js component intends to read and write from the state.

An exception may occur if there is an error in the state or an asynchronous activity that is pending.

Example of useRecoilState hook

import {atom, selector, useRecoilState} from 'recoil';

const tempFahrenheit = atom({
  key: 'tempFahrenheit',
  default: 32,
});

const tempCelsius = selector({
  key: 'tempCelsius',
  get: ({get}) => ((get(tempFahrenheit) - 32) * 5) / 9,
  set: ({set}, newValue) => set(tempFahrenheit, (newValue * 9) / 5 + 32),
});

function TempCelsius() {
  const [tempF, setTempF] = useRecoilState(tempFahrenheit);
  const [tempC, setTempC] = useRecoilState(tempCelsius);

  const addTenCelsius = () => setTempC(tempC + 10);
  const addTenFahrenheit = () => setTempF(tempF + 10);

  return (
    <div>
      Temp (Celsius): {tempC}
      <br />
      Temp (Fahrenheit): {tempF}
      <br />
      <button onClick={addTenCelsius}>Add 10 Celsius</button>
      <br />
      <button onClick={addTenFahrenheit}>Add 10 Fahrenheit</button>
    </div>
  );
}
Highlighted code sample.

Read More: Next.js CSR, SSR, SSG, and ISR: How to Select a Data Fetching Method

What is the useRecoilValue hook?

The useRecoilValue hook causes the React.js component to re-render if there is a change in the Recoil.js atom state.

It returns the value of the given Recoil.js state.

Recoil.js recommends using this hook when a component intends to read state without writing to it, as this hook works with both read-only state and writeable state.

Like the useRecoilState, an exception may occur if there is an error in the state or an asynchronous activity that is pending.

Example of useRecoilValue hook

import {atom, selector, useRecoilValue} from 'recoil';

const namesState = atom({
  key: 'namesState',
  default: ['', 'Ella', 'Chris', '', 'Paul'],
});

const filteredNamesState = selector({
  key: 'filteredNamesState',
  get: ({get}) => get(namesState).filter((str) => str !== ''),
});

function NameDisplay() {
  const names = useRecoilValue(namesState);
  const filteredNames = useRecoilValue(filteredNamesState);

  return (
    <>
      Original names: {names.join(',')}
      <br />
      Filtered names: {filteredNames.join(',')}
    </>
  );
}
Highlighted code sample.

Read More: Next.js Data Fetching: Everything to Know About CSR, SSR, SSG, and ISR

What is the useSetRecoilState hook?

The useSetRecoilState hook in Recoil.js returns a setter function, which can be used asynchronously to change the state by updating the value of the writable Recoil state.

Also, just like the useRecoilState, know that the setter function may either take a new value as an argument or a function (whose purpose is to update), which receives the previous value as a parameter.

Recoil.js recommends using this hook when a component intends to write to state without reading it.

Difference between useRecoilState hook and useSetRecoilState hook in Recoil.js?

When a React.js component uses the useRecoilState() hook to get the setter, it would also automatically subscribe to updates and re-render when the atom or selector changes.

Whereas, useSetRecoilState() allows a component to set the value without subscribing the component to re-render when the value changes.

Example of useSetRecoilState hook

import {atom, useSetRecoilState} from 'recoil';

const namesState = atom({
  key: 'namesState',
  default: ['Ella', 'Chris', 'Paul'],
});

function FormContent({setNamesState}) {
  const [name, setName] = useState('');
  
  return (
    <>
      <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      <button onClick={() => setNamesState(names => [...names, name])}>Add Name</button>
    </>
)}

function Form() {
  const setNamesState = useSetRecoilState(namesState);
  
  return <FormContent setNamesState={setNamesState} />;
}
Highlighted code sample.

What are Atoms in Recoil.js?

In the official documentation, atoms are described as the units of the global state that allows React.js components to subscribe to and make updates to them.

A React.js component subscribed to an atom will re-render when there’s a change in the atom.

To understand what an atom is in a real-life scenario.

Think of recoil.js as a kitchen store for our data. We put items into it and out of it whenever we want.

Now, imagine if we decided to organize this store into sections.

We can have different sections to store items such as a section for fruits, drinks, etc.

An atom in recoil is that section. We can have an atom for a specific use case in our app, and the use case should be specific and contextual.

A Recoil.js atom consists of two main fields

  • key – A unique key. This key should be unique with respect to other atoms and selectors in the entire application.
  • default – A default value that serves as the initial value.

Example of a Recoil.js Atom

Here is an example of a Recoil.js atom:
The name of the atom is noteAge with key noteAge and a default value of 21.

const noteAge = atom({
  key: 'noteAge',
  default: [],
});
Highlighted code sample.

We can access and change the value of the atom from any component within our React.js app.

Example of a Recoil.js Atom using the useRecoilState hook:

import { useRecoilState } from "recoil";

function AgeInputComponent() {
  const [age, setAge] = useRecoilState(ageState);
 return (
    <input
      type="text"
      placeholder="Enter the age"
      onChange={()=>setAge(e.target.value)}
      value={age}
    />
  );
}
Highlighted code sample.

Example of a Recoil.js Atom using the useRecoilValue hook:

import { useRecoilValue } from "recoil";

export default function AgeDisplayComponent() {
  const age = useRecoilValue(ageState);

  return <h3>{age}</h3>;
}
Highlighted code sample.

What are Selectors in Recoil.js?

Selectors in Recoil.js are idempotent or pure functions that accept atoms or any other selectors as their input and return an output that corresponds to the change in input.

They can also be a derived state in Recoil.js.

If only a get function is provided, the selector is read-only and returns a RecoilValueReadOnly object.

If a set is also provided, it returns a writable RecoilState object.

A Recoil.js selector consists of the following main fields:

  • key - A unique string used to identify the selector internally.

    This string should be unique with respect to other atoms and selectors in the entire application.

  • get - This is a function that evaluates the value for the derived state and may return either a value directly or an asynchronous Promise or another atom or selector representing the same type.

  • set? - This is an optional property. If the property is set, the selector will return a writable state.

Example of a Recoil.js Selector

Example of a Recoil.js Selector Using Only get Property

const mySelector = selector({
	key: 'MySelector',
	get: ({get}) => get(myAtom) * 100,
});
Highlighted code sample.

Example of a Recoil.js Selector Using get and set Property

const proxySelector = selector({
  key: 'ProxySelector',
  get: ({get}) => ({...get(myAtom), extraField: 'hi'}),
  set: ({set}, newValue) => set(myAtom, newValue),
});
Highlighted code sample.

App Example of a Recoil.js Selector

Below, we can see a selector agePlusOneState that accepts the ageState we created and returns the age + 1 value.

import { selector } from "recoil";

export const agePlusOneState = selector({
  key: "agePlusOneState", // unique ID (with respect to other atoms/selectors)
  get: ({ get }) => {
    const age = get(ageState);
    const agePlusOne = age+1;
    return agePlusOne;
  },
});
Highlighted code sample.

The get property is the function that is to be computed. It can access the value of atoms and other selectors using the get argument passed to it.

Wrap Off

In this article, we looked at the main concepts and terms you need to know when working with Recoil.js global state management library for React.js.

This is helpful and serves as the key knowledge you may need to completely understand the use of Recoil.js.

If you found this tutorial helpful, consider subscribing to our newsletter and sharing this article.

Next Tutorial — How to Add Text to an Image Using Python

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?