DEV Community

Safal Bhandari
Safal Bhandari

Posted on

Understanding Recoil Selectors in React

Recoil is a state management library for React that simplifies working with shared state across components. Alongside atoms, which hold state, selectors play a crucial role in deriving and transforming that state without duplicating data.


What is a Selector?

A selector in Recoil is a pure function that:

  • Reads one or more atoms (or even other selectors)
  • Computes a derived value
  • Automatically recalculates when its dependencies change

Think of it as a computed property: instead of storing a modified version of your state, you calculate it on demand.


Why Use Selectors?

  1. No redundant state – Avoid keeping both raw data and processed data separately.
  2. Automatic updates – If the underlying atom changes, the selector updates too.
  3. Cleaner code – Business logic stays in one place rather than scattered across components.

Basic Example

Let’s say you have an atom holding a list of items, and you want to know how many there are.

import { atom, selector, useRecoilValue, RecoilRoot } from "recoil";

const itemsState = atom({
  key: "itemsState",
  default: ["Apple", "Banana", "Orange"],
});

const itemCountState = selector({
  key: "itemCountState",
  get: ({ get }) => {
    const items = get(itemsState);
    return items.length;
  },
});

function ItemCount() {
  const count = useRecoilValue(itemCountState);
  return <div>Total Items: {count}</div>;
}

export default function App() {
  return (
    <RecoilRoot>
      <ItemCount />
    </RecoilRoot>
  );
}
Enter fullscreen mode Exit fullscreen mode

Key Points

  • Selectors do not store values — they compute them.
  • They can depend on multiple atoms and selectors.
  • They improve performance by only recalculating when dependencies change.
  • They help keep derived logic separate from components.

Top comments (0)