Recoil
React State Management Library
A React state management library developed by Facebook. Manages global state with Atoms and Selectors and integrates naturally with React Suspense.
React State Management Library
A React state management library developed by Facebook. Manages global state with Atoms and Selectors and integrates naturally with React Suspense.
Recoil is a state management library exclusively for React, released in 2020 by Facebook (now Meta). It started as an internal project of the React team and was developed to address the complexity of existing state management solutions such as Redux and MobX. Recoil's most notable feature is that it is designed to fit the way React works and its philosophy, so global state can be managed intuitively without any separate boilerplate code.
The core concepts of Recoil are Atom and Selector. An Atom is the smallest unit of state, a shared state that any component can subscribe to and update. When an Atom is updated, only the components that subscribe to that Atom are re-rendered. A Selector is a pure function that takes Atoms or other Selectors as input and computes derived state. Asynchronous logic can also be handled naturally within a Selector, so data fetching and state management can be integrated.
Recoil was designed to overcome the limitations of the React Context API. The Context API is useful for sharing global state, but it has a performance problem: when a Context value changes, all components that subscribe to that Context are re-rendered. Recoil manages state in fine-grained Atom units, so only the components that subscribe to the state that actually changed are selectively re-rendered. In addition, unlike Redux, it lets you work with global state through a simple API like useState, without complex patterns such as actions, reducers, and dispatch.
Recoil integrates seamlessly with React Suspense. When a Selector returns asynchronous data, Suspense's fallback UI is automatically displayed while the data is loading. This enables declarative asynchronous state management and also works well with the Concurrent features of React 18. In addition, through Atom Effects, side effects such as local storage synchronization, logging, and state initialization can be managed at the Atom level.
// Recoil Atom μ μ - μνμ μ΅μ λ¨μ
import { atom } from 'recoil';
// μ¬μ©μ μ 보 Atom
export const userState = atom({
key: 'userState', // κ³ μ μλ³μ (νμ)
default: {
name: '',
email: '',
isLoggedIn: false
}
});
// μ₯λ°κ΅¬λ Atom
export const cartState = atom({
key: 'cartState',
default: [],
// Atom Effectsλ‘ λ‘컬 μ€ν λ¦¬μ§ λκΈ°ν
effects: [
({setSelf, onSet}) => {
// μ΄κΈ°ν μ λ‘컬 μ€ν 리μ§μμ λΆλ¬μ€κΈ°
const savedCart = localStorage.getItem('cart');
if (savedCart) {
setSelf(JSON.parse(savedCart));
}
// μν λ³κ²½ μ λ‘컬 μ€ν 리μ§μ μ μ₯
onSet((newValue) => {
localStorage.setItem('cart', JSON.stringify(newValue));
});
}
]
});
// ν
λ§ μ€μ Atom
export const themeState = atom({
key: 'themeState',
default: 'light'
});
// Selector - Atomμμ νμλ μν κ³μ°
import { selector } from 'recoil';
import { cartState, userState } from './atoms';
// μ₯λ°κ΅¬λ μ΄μ‘ κ³μ° Selector
export const cartTotalSelector = selector({
key: 'cartTotalSelector',
get: ({get}) => {
const cart = get(cartState);
return cart.reduce((total, item) =>
total + item.price * item.quantity, 0
);
}
});
// λΉλκΈ° Selector - API λ°μ΄ν° νμΉ
export const userOrdersSelector = selector({
key: 'userOrdersSelector',
get: async ({get}) => {
const user = get(userState);
if (!user.isLoggedIn) {
return [];
}
// λΉλκΈ° λ°μ΄ν° νμΉ (Suspense μλ ν΅ν©)
const response = await fetch(
`/api/users/${user.email}/orders`
);
return response.json();
}
});
// μ°κΈ° κ°λ₯ν Selector
export const cartItemCountSelector = selector({
key: 'cartItemCountSelector',
get: ({get}) => {
const cart = get(cartState);
return cart.reduce((count, item) =>
count + item.quantity, 0
);
},
set: ({set}, newValue) => {
// μ 체 μ΄κΈ°ν λ± νΉλ³ν λμ
if (newValue === 0) {
set(cartState, []);
}
}
});
// μ»΄ν¬λνΈμμ Recoil μν μ¬μ©νκΈ°
import { Suspense } from 'react';
import {
useRecoilState,
useRecoilValue,
useSetRecoilState
} from 'recoil';
import { cartState, cartTotalSelector, userOrdersSelector } from './store';
function Cart() {
// useStateμ²λΌ [κ°, setter] λ°ν
const [cart, setCart] = useRecoilState(cartState);
// μ½κΈ° μ μ© (리λ λλ§ μ΅μ ν)
const total = useRecoilValue(cartTotalSelector);
// μ°κΈ° μ μ© (ν΄λΉ μ»΄ν¬λνΈλ κ° λ³κ²½μ 리λ λ μλ¨)
const setCartOnly = useSetRecoilState(cartState);
const addItem = (product) => {
setCart((prev) => {
const existing = prev.find(item => item.id === product.id);
if (existing) {
return prev.map(item =>
item.id === product.id
? { ...item, quantity: item.quantity + 1 }
: item
);
}
return [...prev, { ...product, quantity: 1 }];
});
};
return (
<div>
<h2>μ₯λ°κ΅¬λ ({cart.length}κ° μν)</h2>
{cart.map(item => (
<div key={item.id}>
{item.name} x {item.quantity}
</div>
))}
<p>μ΄μ‘: {total.toLocaleString()}μ</p>
{/* λΉλκΈ° Selector + Suspense */}
<Suspense fallback={<p>μ£Όλ¬Έ λ΄μ λ‘λ© μ€...</p>}>
<OrderHistory />
</Suspense>
</div>
);
}
function OrderHistory() {
// λΉλκΈ° Selector μ¬μ© - μλμΌλ‘ Suspense μ²λ¦¬
const orders = useRecoilValue(userOrdersSelector);
return <div>{orders.length}κ°μ μ£Όλ¬Έ λ΄μ</div>;
}
Frontend Lead Park:
"We need to decide which library to use for state management in the new dashboard project. Redux and Recoil are the current candidates."
Junior Developer Kim:
"I recommend Recoil. Unlike Redux, you can define an atom right away and use it like useState, without setting up actions, reducers, or middleware. The learning curve is low and there's less boilerplate."
Senior Developer Lee:
"Hold on, Recoil is no longer being actively developed by Facebook. There have been no major updates since 2024, and the maintainers have left. Adopting it in a new project carries risk."
Frontend Lead Park:
"Then what alternatives are there? Ones that keep Recoil's strengths."
Senior Developer Lee:
"Jotai has almost the same API as Recoil, and it is lighter and actively maintained. Zustand is also good. It's more concise and also integrates with Redux DevTools. From a long-term maintenance perspective, let's consider these."
Reviewer:
"In this PR, all the state is put into one giant Atom, which means you can't take advantage of Recoil's strengths. Even if only part of it changes, all the subscribing components are re-rendered."
Author:
"Ah, I tried to manage it with a single store like the Redux pattern. How should I split up the Atoms?"
Reviewer:
"In Recoil, it's better to create several small Atoms by concern, for example userAtom, cartAtom, and uiAtom. And create derived state with Selectors. If you make values computed from cart, like cartTotalSelector, separately, dependencies are tracked automatically."
Author:
"What about asynchronous data? Right now I'm fetching in useEffect and calling setState."
Reviewer:
"Use an asynchronous Selector. If you fetch with async/await in the get function, it integrates with Suspense automatically. You don't need to manage loading state separately; handling it with the Suspense fallback makes the code much cleaner."
Interviewer:
"You said you have experience using Recoil. What did you like about it compared with Redux?"
Candidate:
"Recoil manages state in atom units, so only the components that need it are re-rendered. With Redux, since you subscribe to a single global store, unnecessary re-renders were easy to cause. Also, asynchronous selectors integrate naturally with Suspense, which made handling loading state simple."
Interviewer:
"There is some controversy about Recoil's development being discontinued. What would you do for a new project?"
Candidate:
"That's right. For a new project, I'd recommend Jotai. It has almost the same API as Recoil, a small bundle size, and is actively maintained. With my existing Recoil experience, switching to Jotai was also easy. Or, if the state isn't complex, Zustand is also a good choice."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
Recoil has had no major updates since 2024, and the core maintainers have left Facebook. The experimental tag is also still in place, so long-term maintenance risk should be considered when adopting it in a new project. Existing Recoil projects are fine for now, but for new projects, consider alternatives.
Jotai offers an atomic pattern similar to Recoil's, and it is lighter and actively maintained. Zustand provides a simpler API and even supports Redux DevTools. React Query/TanStack Query specializes in server state management. Choose the library that fits your project requirements.
Existing Recoil projects are easy to migrate to Jotai, because the atom and selector concepts are almost identical and the APIs are similar. Since gradual migration is possible, you can switch module by module rather than changing everything at once.
The key of every Atom and Selector must be unique across the entire application. Duplicate keys cause runtime errors. Establish a naming convention (e.g., 'feature/atomName') and have the whole team use it consistently.