Recoil: How a new JS library to handle React state…

3 min readNov 20, 2020

Component state in React is passed through Parent and Child, which requires the use of Props to pass state.

Definition taken from the Recoil API:

‘Recoil lets you create a data-flow graph that flows from atoms (shared state) through selectors (pure functions) and down into your React components. Atoms are units of state that components can subscribe to. Selectors transform this state either synchronously or asynchronously.’

State is passed through Atoms, a new form of passing state which differs from the cumbersome Redux method, which is free from the inheritance model we are accustomed to in React and JS.

Here’s an example of state passed via a Recoil Atom:

const fontSizeState = atom({key: 'fontSizeState',default: 14,});

Recoil state is called using hooks, as seen in the hook below useRecoilState:

function FontButton() {const [fontSize, setFontSize] = useRecoilState(fontSizeState);return (<button onClick={() => setFontSize((size) => size + 1)} style={{fontSize}}>Click to Enlarge</button>);}

Other functional components have access to the fontSizeState without needing to inherit the FontButton

function Text() {const [fontSize, setFontSize] = useRecoilState(fontSizeState);return <p style={{fontSize}}>This text will increase in size too.</p>;}

A selector is a pure function that accepts atoms or other selectors as input. Selectors and Atoms are interchangeable in their use.

Here is an example of a selector using fontSizeLabelState

const fontSizeLabelState = selector({key: 'fontSizeLabelState',get: ({get}) => {const fontSize = get(fontSizeState);const unit = 'px';return `${fontSize}${unit}`;

Composer, Designer, Educator