Recoil is a state management library for React, so you need to have React installed and running to use Recoil. The easiest and recommended way for bootstrapping a React application is to use Create React App:
For more ways to install Create React App, see the official documentation.
The Recoil package lives in npm. To install the latest stable version, run the following command:
Or if you're using yarn:
Or if you're using bower:
Components that use recoil state need
RecoilRoot to appear somewhere in the parent tree. A good place to put this is in your root component:
We'll implement the
CharacterCounter component in the following section.
An atom represents a piece of state. Atoms can be read from and written to from any component. Components that read the value of an atom are implicitly subscribed to that atom, so any atom updates will result in a re-render of all components subscribed to that atom:
Components that need to read from and write to an atom should use
useRecoilState() as shown below:
A selector represents a piece of derived state. Derived state is a transformation of state. You can think of derived state as the output of passing state to a pure function that modifies the given state in some way:
We can use the
useRecoilValue() hook to read the value of
Below is the finished product: