Compute a Value in Recoil Using a Selector

Share this video with your friends

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)