Recoil.js and it’s Dynamic State

Alex Duterte
3 min readAug 31, 2020

When Recoil was released in May, I thought it was amazing. One of the greatest features they showcased was using atoms for dynamic state, but when I explored recoil at first, I only used it for basic state management. You can check my blog post about getting started with recoil here.

Today I am going to tackle setting up Dynamic State using Atoms.

Let’s say we have a bunch of different components somewhere in the app and different components to change the state of those components. For this blog I’m going to build a simple app where we can change the background color of a box.

One of the issues we face is that we don’t know many boxes we will have. We could theoretically create a thousand different boxes.

The great thing with recoil is that we can manage the state of all these boxes using code for 1 atom.

The Atom

The boxesAtom is just an array (default empty) of box objects.

On line 8 we have the boxAtom. Notice we are using (id) to target the specific object we want to change the state of. We’ll dive into that next when we get to the components.

The Components

the boxesAtom on line 3 is an array of each box object.

On line 25 we have a Controller component for every box object in our app. Note the id={index + 1}. We’re going to be passing an id as props. The same thing is happening on line 30. For every box object in our app, we’re going to display a box.

Inside the Component

We import the boxAtom and useRecoilState normally but let’s look at what’s happening on line 7. Normally we would use something like useRecoilState(boxAtom), but here we are using useRecoilState(boxAtom(props.id))

By passing the argument of props.id we can target that specific atom.

changing the selection for the 4th box only effects the background color of the 4th box!

Inside the Box Component

It’s pretty much the same thing going on inside the Controller component except we are only using the useRecoilValue hook since we won’t be setting state at all within this component.

So that’s my quick simple guide on setting up Dynamic States using Recoil!

--

--