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?
- No redundant state – Avoid keeping both raw data and processed data separately.
- Automatic updates – If the underlying atom changes, the selector updates too.
- 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>
);
}
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)