Recoil is a state management library for ReactJS, made by the developers of React. React has the major limitation of components only sharing state through a common ancestor. Recoil allows state to be stored individually and separately from the components through the use of atoms and selectors. The components then call on the atoms as needed. This creates a data-flow graph going from the atoms through the selectors to the components.
Atoms
Atoms are individual units of shared state which are undateable and subscribable. When an atom is updated, each subscribed component is re-rendered with the new value. Components that read the value of the atom are automatically subscribed to the atom. Atoms are created using the atom function:
const textState = atom({
key: ‘textState’, // must be a unique value among atoms and selectors
default: ‘’,
});
To read the contents of this atom we use useRecoilState()
which takes a passed atom and returns a two element array of a getter and a setter. The setter is a function which takes a value and returns a transformation which is then assigned to the default of the atom.
Selectors
Selectors represent derived state or a transformation of state. A way to conceptualize it is to imagine a derived state as the output of passing state into a pure function which then outputs an alteration of that state without modifying the original state.
const charCountState = selector({
key: 'charCountState',
get: ({get}) => {
const text = get(textState);
return text.length;
},
});
This example uses the atom textState
by getting the default and returning the length of the string. We can then use this value by calling the useRecoilValue()
method which only returns a getter, since selectors are not updatable.
With this system of atoms and selectors, we can easily distribute state to whichever components might need it, while avoiding the ones that don't. This saves valuable time and memory when rendering components.
Top comments (0)