Skip to content

Selector

Course: Recoil - chapter 7

A selector represents a piece of derived state. You can think of derived state as the output of passing state to a pure function that derives a new value from the said state.

Derived state is a powerful concept because it lets us build dynamic data that depends on other data.

  • Add a selector
const even = selector({
key: 'isEven',
get: ({ get }) => {
const count = get(counter);
return count % 2;
},
})
  • Add an IsEven component
function IsEven() {
const isEven = useRecoilValue(even);
return <div>
{isEven ? "Even" : "Odd"}
</div>
}
  • Change the increase function
function increase() {
setCount(c => c + 2)
}