1. 2
    Create Shared State with Recoil in a React App
    3m 40s

Create Shared State with Recoil in a React App

InstructorChris Achard

Share this video with your friends

Send Tweet

We'll create a new bit of shared state (called an "atom" in Recoil) by importing atom from Recoil and setting a unique key and default value:

import {
  atom
} from 'recoil'

const gameScore = atom({
  key: 'gameScore',
  default: 0
})

Then we can use that gameScore by calling the Recoil hook useRecoilState

import {
  useRecoilState
} from 'recoil'

...

  const [score, setScore] = useRecoilState(gameScore)

That looks a lot like a local useState call - but is different because it creates the state in Recoil, which can then be used in this component, or in any other component in the tree (underneath the same RecoilRoot)