Compute a Value in Recoil Using a Selector

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet

To compute a value from one or more values stored in Recoil, we can create a "selector".

First import selector from Recoil, and then call it with an object that has two keys: key and get:

import { selector } from recoil;
...
const paperSize = selector({
  key: 'paperSize',
  get: ({get}) => {
    const score = get(gameScore)
    return 100 + (score * 5)
  }
})

Inside of the get function we can get the current value of the gameScore atom from recoil, and then compute a new value from that to return to our game. Then we can get the value using useRecoilValue:

import { paperSize } from './selectors'
...
const size = useRecoilValue(paperSize)

Chris Achard: [0:00] Say we want to do something based on that score like set the fontSize, which is fixed at 100. We could just do a calculation here to set the fontSize. We can also write something called a selector.

[0:11] Let's touch a new file. We're going to call that src/selectors.js. In selectors, we're going to import { selector } from 'recoil'. Selectors are going to allow us to compute a value based on a current value in an atom. We need to import that atom first. We're going to import { gameScore } from './atoms' and then we can use it.

[0:40] Let's make a new selector. We'll call it the paperSize. That is going to call this selector() function from recoil and that takes an object. That object has a key just like the atoms do. We're going to call that paperSize.

[0:54] Remember, this key has to be unique across atoms and selectors. Then it has a key called get. That's supposed to be a function. We're going to have a function here. The argument to that function is an object. One of the items inside that object is called get. This will allow us to get the game score from that atom.

[1:14] We can pull the current score with score = get(gameScore). From this function here, we can return a new value. We'll start at a size of 100 and then we'll return the score * 5. Each time we click the size will go up by five. We can export from this file our paperSize. Now we can use this.

[1:40] Let's go into our game.js and we can import { paperSize } from './selectors'. We can't use this directly. We have to wrap this in useRecoilValue. Down here, we have our score first and then we can say our size is going to be useRecoilValue(paperSize). Instead of our 100 down here, this size will start at 100 and will count up as we click on the paper.

[2:12] Let's save it and refresh. As we click up, the paper gets bigger as our score goes up. We're able to use this computed value from our selector and we can use it here or in any other component in our tree.