Recoil is a state management library for React that makes it easier to manage and share state between components without falling into prop drilling nightmares. Below, we’ll explore the core concepts you need to get started, using just a few essential APIs.
1. RecoilRoot
Every Recoil-based application must wrap its top-level component tree inside a <RecoilRoot>
.
Think of it as the provider that enables Recoil’s state management features. Without it, Recoil atoms and selectors won’t work.
import { RecoilRoot } from 'recoil';
import App from './App';
function Root() {
return (
<RecoilRoot>
<App />
</RecoilRoot>
);
}
2. atom
An atom is the smallest unit of state in Recoil.
It’s similar to a useState
variable, but global — any component that uses it will read and update the same shared value.
import { atom } from 'recoil';
export const countAtom = atom({
key: 'countAtom', // unique ID
default: 0, // initial value
});
3. useRecoilState
This hook is like useState
but works with Recoil atoms.
It returns the current value and a setter for the atom.
import { useRecoilState } from 'recoil';
import { countAtom } from './store';
function Counter() {
const [count, setCount] = useRecoilState(countAtom);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
4. useRecoilValue
If you only want to read the atom’s value and don’t need to update it, use useRecoilValue
.
This avoids unnecessary re-renders from setter functions.
import { useRecoilValue } from 'recoil';
import { countAtom } from './store';
function DisplayCount() {
const count = useRecoilValue(countAtom);
return <p>Current count: {count}</p>;
}
5. useSetRecoilState
When you only want to update the atom’s value but don’t need to read it, use useSetRecoilState
.
This is handy for event handlers or actions.
import { useSetRecoilState } from 'recoil';
import { countAtom } from './store';
function IncrementButton() {
const setCount = useSetRecoilState(countAtom);
return <button onClick={() => setCount(c => c + 1)}>Increment</button>;
}
Why Recoil Is Useful
- No Prop Drilling – Share state across distant components without passing props manually.
- Better Read/Write Control – Separate reading and writing for optimized renders.
- Scalable – Easy to maintain in large applications.
With just these five tools — RecoilRoot, atom, useRecoilState, useRecoilValue, useSetRecoilState — you can handle most global state needs in your React projects.
Top comments (0)