Setting Up State Management (Recoil) for React Application
Recoil is an atomic state manager from Meta. Atoms and selectors form a state graph that React uses for granular re-renders. Natively supports Concurrent Mode, Suspense, and async selectors.
Suitable for large React applications with complex state where fine-grained subscription granularity and built-in async support matter.
What's Involved
Initializing Recoil in a project, designing atoms and selectors, setting up async data through Suspense, typing, devtools, persistence, atom families for lists.
Installation
npm install recoil
# devtools
npm install recoil-devtools
Wrap the application in RecoilRoot:
import { RecoilRoot } from 'recoil'
function App() {
return (
<RecoilRoot>
<Router />
</RecoilRoot>
)
}
Atoms
import { atom } from 'recoil'
export const authTokenAtom = atom<string | null>({
key: 'authToken',
default: null,
})
export const cartItemsAtom = atom<CartItem[]>({
key: 'cartItems',
default: [],
})
export const sidebarOpenAtom = atom<boolean>({
key: 'sidebarOpen',
default: false,
})
Atom keys are unique strings across the entire application. Use domain prefix convention: 'cart/items', 'auth/token'.
Selectors
import { selector } from 'recoil'
export const cartTotalSelector = selector<number>({
key: 'cartTotal',
get: ({ get }) => {
const items = get(cartItemsAtom)
return items.reduce((sum, item) => sum + item.price * item.quantity, 0)
},
})
export const cartCountSelector = selector<number>({
key: 'cartCount',
get: ({ get }) => get(cartItemsAtom).reduce((sum, i) => sum + i.quantity, 0),
})
Selectors are memoized — they recalculate only when dependent atoms change.
Timeline
Basic Recoil setup — 1–2 hours. Async selectors with Suspense — 2–3 hours. Complex selector graph — 1 day.







