1. 3
    Use Selectors to Calculate Derived Data Based on State Stored within a Recoil Atom
    2m 36s

Use Selectors to Calculate Derived Data Based on State Stored within a Recoil Atom

InstructorTomasz Łakomy

Share this video with your friends

Send Tweet

Recoil allows us to use atoms in order to store pieces of state. More often than not in our apps we need to use data that derives from our application state (for instance to multiply height and width stored within a state to calculate area of an element).

Luckily Recoil provides us with a powerful tool to automatically re-calculate derived state value whenever an piece of state changes - selectors.

A selector is a pure function that accepts atoms or other selectors as input. When these upstream atoms or selectors are updated, the selector function will be re-evaluated.

In this quick lesson we're going to learn how to use a selector in order to automatically calculate a square of a number whenever a value stored within an atom is going to change

Nate Holloway
~ 4 years ago

What is the advantage over:

const squareState = (number) => number**2;

const squareNumber = squareState(useRecoilValue(numstate));

Reuse: The selector can be used in all components.

Jose Torres
~ 4 years ago

where do we should define the selector? In the same place we defined the atom or in other place?

Eleonora Lester
~ 4 years ago

If we need to reuse that selector, how do we pass the atom to it if we move the selector to a separate file?