Recoil - The React State Management Library

JayakrishnaJayakrishna
5 min read

Recoil...

Recoil is a state Management library in react which was developed by the Facebook to process the high complex application state.

Why Recoil?....

Before Knowing about the Recoil we need to know about the Prop Drilling and Context hook which is used to prevent the Prop Drilling i.e passing the props from parent component to the child Component due to this unnecessary re-render occurs but the context hook only handles the prop drilling but not the re-rendering for this we uses an external library

There are types in state management libraries

  • Redux

  • Recoil

  • zustand

and few More....

Installation...

npm install recoil

Run this syntax in the terminal to get library locally in the system

To underStand recoil we need to know about two main terms in recoil

  • Atoms

  • Selectors

Atoms

These are the fundamental units of state in react. They encapsulate individual pieces of application data that can be read from and updated within your components.

The syntax Looks like

import { atom } from "recoil"

export const countAtom = atom({
    key: "countAtom",
    default: 0
})

if you see the countAtom variable it contains two terms Key and default in this key should be different for every atom it shouldn't be the same and default value is the initial value of the state

Selectors

Selectors are derived state values. They allow you to define computations based on other atoms or selectors. This approach is ideal for complex logic determining a state value.

For example let's take there are two state and we need to add there values...

import { atom, selector } from "recoil"
//Declaring the Atoms
export const messageAtom = atom({ 
    key: "messageAtom",
    default: 0
})
export const notificationAtom = atom({
    key: "notificationAtom",
    default: 121
})
//Adding those Atoms using selectors
export const totalValueSelector = selector({
    key: "totalValueSelector",
    get: ({ get }) => {
        const messageAtomCount = get(messageAtom)
        const notificationAtomCount = get(notificationAtom)
        return (
            messageAtomCount + notificationAtomCount
        )}
})

Selector also takes two inputs one is key which is similar to atom and other is get which takes the logic to derive the value from the Atom using the function.

Selectors are used for Asynchronous Data fetch calls

There are few more things which are need to be known they are Recoil Hooks

  • useRecoilValue()

  • useRecoilState()

  • useSetRecoilState()

These are used to get the values from the atoms

useRecoilValue() :-

useRecoilValue() was used to get only the initial state value from the atom which are declare the syntax is

let's take the previous example

import { useRecoilValue } from 'recoil'
function Count(){
  const notificationCount = useRecoilValue(notificationAtom)
  return (
        {notificationCount}
    )
}

useRecoilState() :-

useRecoilState() is used to get the both value from atom like default value and the state variable value

it's syntax is

import {useRecoilState} from 'recoil'
function countVariable(){
  const [count, setCount] = useRecoilState(countAtom)
return (
    <>
      <button onClick={() => {
        steCount(c => c - 1)
      }}>count is ({count})</button>
    </>
  )
}

useSetRecoilState() :-

useSetRecoilState() was used to get only the setValue function from the Atom to update and it not get it's value

It has the similar syntax with previous

import {useSetRecoilState} from 'recoil'
function countVariable(){
  const  setCount = useSetRecoilState(countAtom)
//it can only update the but can't print on DOM
return (
    <>
      <button onClick={() => {
        steCount(c => c - 1)
      }}>Update Value</button>
    </>
  )
}

And Recoil provides two powerful concepts for managing the collection of Atoms and Selectors they are

  • atomFamily()

  • selectorFamily()

atomFamily() :-

An atom family is essentially a factory that generates atoms based on a key. It allows you to define a template for creating atoms with unique identities while sharing common logic.

import {atomFamiliy} from 'recoil'
export const TODOS = [{
    id: 1,
    title: "Go to Gym",
    description: "Hit the gym from 7-9"
}, {
    id: 2,
    title: "Go to eat food",
    description: "Eat food from from 9-11"
},]

export const todoFamily = atomFamily({
    key: "todoFamily",
    default: id => {
        return TODOS.find((x => x.id === id))
    }
});

and further we can use Recoil Hooks to render these values on DOM.

In atomFamily when we need to do asynchronous calls selectorFamily is used.

selectorFamily() :-

Similar to atom families, selector families create a family of selectors based on a key. This is useful when you need to derive state values with a common logic but require different inputs or calculations depending on the key.

syntax is

import { selectorFamily } from 'recoil'
import axios from 'axios'

export const todoAtomFamily = atomFamily({
    key: "todoFamily",
    default : selectorFamily({
        key : "todoSelectorFamily",
        get : id => async ({get})=>{
            const res = await axios.get(`Backend url which returns value`)
            return res.data.todo;
        }
    })
})

Difference...

  • State vs. Derived Values: Atom families create stateful atoms, while selector families create derived selectors that compute values based on other atoms or selectors

  • Modification: Atoms are directly modifiable using useRecoilState, whereas selectors cannot be modified directly.

atoms uses selectors inside them and only atomFamily uses selectorFamily inside them

fetch calls from the backend are done using the selectors

There are Other Two important Recoil Hooks which are used when Backend fetch calls are done..

  • useRecoilValueLoadable()

  • useRecoilStateLoadable()

I Think this has too much Learning And let's continue in next until Then Keep Smiling

Here is my Twitter and LinkedIn Profiles let's connect....

1
Subscribe to my newsletter

Read articles from Jayakrishna directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jayakrishna
Jayakrishna