DEV Community

Cover image for Atom Family in Recoil for Statement Management — Nextjs
Next Dev
Next Dev

Posted on

Atom Family in Recoil for Statement Management — Nextjs

Welcome friends. This blog post will teach you how to use the recoil atom family to update the specific atom in recoil state management.

If you understand Hindi, 🥳 this is for you 👇

If you want to know the basics of recoil
Recoil State Managment

🤔Situation

When to use atom Family in recoil.

Suppose, you got a project for making a todo app. Now, you have to make a website where you can edit each todo and also create a new todo.

Firstly, you created a website that uses atoms for storing all the todos, and then you used a selector family for changing a specific todo.

Sample Source Code — https://github.com/nextdev1111/atomfamily-tutorial

Now, you can use this code in your ide.

🤕Problem with this code

There’s a major problem with this code. The problem is that if you update a single todo title, then all the components, which use the atoms will rerender.

This is because, when you change one todo, you ultimately change the whole list which forces all the components to re-render and it takes a lot of power which essentially decreases performance.

😍In simple words

In simple words, the atoms family takes a param and changes a specific item **but atoms don’t take a param and change the **whole atom.

🤔Solution

You can use atomFamily which helps you to edit a specific todo. This is very performant in big sites.

How to use it?

Taking this website as an example, you need to follow these steps:

Step1: Remove Selectors and Add AtomFamily

First, Delete the selector's folder and their imports.

Go to atoms.ts file and change this

Step2: Change the index file

Go to index.tsx file.

Step3: Change the component — ‘Todo’

Go to todo.tsx file in the components folder.


If you want to understand more, feel free to message me at
[Join the Next Dev Discord Server!]
https://discord.gg/hN4Wc5VR4M

Top comments (0)