DEV Community

harshchandwani
harshchandwani

Posted on

Recoil: Cheatsheet

Hello Developers,
This article was written when I was reading and learning to use Recoil for a project. I know about Redux, but Recoil is much more used in Open-Source and is gaining popularity, so this is a small article with shortcuts to use Recoil.

For more information: https://recoiljs.org/

Installation:
For npm: npm install recoil
For CDN: <script src = "https://cdn.jsdelivr.net/npm/recoil@0.0.11/umd/recoil.production.js"></script>

To use Recoil, you need to make every component use Recoil.

//App.js
import React from 'react'
import { RecoilRoot } from 'recoil'
import ChildComponent from './component/ChildComponent'
const App = () => {
  return (
      <RecoilRoot>
        <ChildComponent />
      </RecoilRoot>   
  )
}
Enter fullscreen mode Exit fullscreen mode

Atoms are the smallest units of state in Recoil, serving as fundamental variables. This article guides you through creating and using an Atom, providing a clean structure for managing state variables within React components.

Setting Up Your Atom:
Organize your state-related code in a 'utils' file for better project structure management.

//Atom.js
import { atom } from "recoil"
export const counterAtom = atom({
    key: 'counterAtom', //A unique identifier for the Atom, ensuring uniqueness across your application.
    default: '12' //The initial value of the Atom, is set to '12'. Adjust based on your desired initial state.
});
Enter fullscreen mode Exit fullscreen mode

Now, as you have created an atom or variables, how to access them?
There are multiple ways.
Let's goπŸš€

//Component.js

export const Component = () => {
  const xAtom = useRecoilValue(xAtom); //only access to value
  const [yAtom, setyAtom] = useRecoilState(yAtom); //same as useState
  const setZAtom = useSetRecoilState(zAtom); //on set function, no access to the current value, but can change using set variable
  return (
    <>
      <p>xAtom</p>
      <button onClick={() => setyAtom(yAtom+ 1)}>yAtom</button>
      <button onClick={() => setZAtom(c + 1)}>zAtom</button>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

But what if I want to combine two atoms?

  • One way is to do that in component [useMemo]
  • Other is to use a selector
//Atom.js
import { atom, selector } from "recoil"
export const xAtom = atom({
    key: 'xAtom',
    default: 10
})
export const yAtom = atom({
    key: 'yAtom',
    default: 11
})

export const sum = selector({
    key: 'sum',
    get: ({get}) => {
        return (
            xAtom.xAtom + 
            yAtom.yAtom
        )
    }
})
Enter fullscreen mode Exit fullscreen mode

How to accept and store backend calls

import { atom, selector } from "recoil"
import axios from "axios";
export const information = atom({
    key: 'information',
    default: selector({
        key: "informationSelector", 
        get: async () => {
            const res = await axios.get("somerandomsite");
            return res.data
        }
    })
})
Enter fullscreen mode Exit fullscreen mode

What is Atom Family

  • When you are making Todo, how will store multiple todo, creating different atom for different todo?
  • No, for this Atom Family is here
  • Let's have an example
//Atom.js
import { atomFamily } from "recoil"
const TODOS = [{
    id: 1,
    title: "Go to GYM",
    description: "Hit the gym"
}, {
    id: 2,
    title: "Go to Office",
    description: "Code something new"
}]

export const todoAtomFamily = atomFamily({
    key: "todoAtomFamily",
    default: id => {
        return TODOS.find(x => x.id === id)
    },
});
Enter fullscreen mode Exit fullscreen mode
//App.js
import {todoAtomFamily } from './Atom'
const App = () => {
  return (
      <RecoilRoot>
        <Main />
      </RecoilRoot>   
  )
}
const Main = () => {
      <Todo id={1} />
  )
}
function Todo({id}){
  const currentTodo = useRecoilValue(todoAtomFamily(id));
  return (
    <>
      {currentTodo.title}
      {currentTodo.description}
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Selector Family

//Atom.js
import { atomFamily, selectorFamily } from "recoil";
import axios from "axios";

export const todosAtomFamily = atomFamily({
  key: 'todosAtomFamily',
  default: selectorFamily({
    key: "todoSelectorFamily",
    get: (id) => async ({get}) => {
      const res = await axios.get(`https://sum-server.100xdevs.com/todo?id=${id}`);
      return res.data.todo;
    },
  })
});
Enter fullscreen mode Exit fullscreen mode
//App.js
const [todo, setTodo] = useRecoilState(todosAtomFamily(id));
Enter fullscreen mode Exit fullscreen mode

That's all about it. Hope you get an idea of what recoil is and how to use it.
I know the Recoil selector family is a little difficult and hard to understand, but it also used less.

Thanks
Harsh Chandwani
Follow for more: https://twitter.com/heyy_harshh

Top comments (0)