DEV Community

Arhan Khan
Arhan Khan

Posted on

Recoil for Beginners: Simple State Management for React

Recoil is a state management library for React made by Facebook. It solves a specific problem: sharing state between components without prop drilling and without the boilerplate of Redux. If you have ever passed props through four components just to reach one button, Recoil is worth learning.

The two core ideas are atoms and selectors. An atom is a single piece of state:

import { atom, useRecoilState } from "recoil";

const countState = atom({
  key: "countState",
  default: 0,
});

function Counter() {
  const [count, setCount] = useRecoilState(countState);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
Enter fullscreen mode Exit fullscreen mode

Any component can read or update that atom, no matter where it sits in the tree. You just wrap your app in RecoilRoot once:

import { RecoilRoot } from "recoil";

<RecoilRoot>
  <App />
</RecoilRoot>
Enter fullscreen mode Exit fullscreen mode

Selectors are derived state — values computed from atoms, like a filtered list:

import { selector, useRecoilValue } from "recoil";

const doubledState = selector({
  key: "doubledState",
  get: ({ get }) => get(countState) * 2,
});

const doubled = useRecoilValue(doubledState);
Enter fullscreen mode Exit fullscreen mode

Only components that use a particular atom re-render when it changes. That is the big win over Context, where one value change can re-render everything below the provider.

Who is it for? React developers whose apps have outgrown useState and prop drilling but do not need Redux. Small to medium apps with shared state — theme, user data, filters, carts — are the sweet spot.

The limits: Recoil is still officially experimental in some senses, and its community is smaller than Redux or Zustand. There is no built-in devtools as polished as Redux DevTools. And for very large apps with complex async logic, you may still want something heavier.

Start today: take one piece of state you currently pass through three or more components and move it into an atom. If the code gets shorter and clearer, Recoil has earned its place in your project.

Top comments (0)