πŸ’» Programming

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.

πŸ“– Detailed Explanation

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.

πŸ’» Code Example

atoms.js - Atom definition
// 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'
});
selectors.js - Selector (derived state)
// 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, []);
        }
    }
});
Cart.jsx - Usage in a component
// μ»΄ν¬λ„ŒνŠΈμ—μ„œ 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>;
}

πŸ—£οΈ Example Conversations in Practice

Technical Meeting Choosing Between Redux and Recoil for State Management

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."

Code Review Recoil State Design Review

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."

Technical Interview Choosing a State Management Library

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

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More