
Recoil.js Cheatsheet
This Recoil.js cheatsheet provides a concise reference to key Recoil concepts, including atoms, selectors, and state management in React applications. It covers advanced topics such as atom families, selector families, asynchronous state handling, and performance optimization, with practical code examples for each feature. Designed to help developers efficiently manage global state in React, this guide serves as a quick resource for building scalable and responsive applications using Recoil.
Table of Contents
- Introduction
- Installation
- Getting Started with Recoil
- Atoms
- Selectors
- Atom Families
- Selector Families
- RecoilRoot
- Asynchronous State Management
- State Persistence
- Debugging Tools
- Performance Optimization
Introduction
Recoil is a state management library that was built for React applications. It enables a straightforward and scalable approach to transactions with atoms and selectors and reactivity in concurrent mode.
Installation
Install Recoil via npm install recoil or use a CDN for direct browser integration.
npm install recoil
For CDN usage, add the following script:
<script src="https://cdn.jsdelivr.net/npm/recoil/umd/recoil.production.js"></script>
Getting Started with Recoil
Wrap your React app
import { RecoilRoot } from 'recoil'; function App() { return ( <RecoilRoot> {/* Components */} </RecoilRoot> ); }
Atoms
Atoms represent pieces of state that components can read from and write to independently.
Creating Atoms
Atoms are defined using atom() with a unique key and a default value to store the global value.
import { atom } from 'recoil'; const counterState = atom({ key: 'counterState', // Unique identifier default: 0, // Initial value });
Accessing Atom States
- Read-Only Access: Use useRecoilValue.
- Read and Write Access: Use useRecoilState.
- Write-Only Access: Use useSetRecoilState.
Example:
import { useRecoilValue, useRecoilState, useSetRecoilState } from 'recoil'; function Example() { const counter = useRecoilValue(counterState); const [count, setCount] = useRecoilState(counterState); const increment = useSetRecoilState(counterState); return ( <> <p>Counter: {counter}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </> ); }
Selectors
Selectors are derived state functions that compute values based on atom states.
Basic Selectors
Selectors allow computed state transformations using the get function.
import { selector } from 'recoil'; const doubledCounter = selector({ key: 'doubledCounter', get: ({ get }) => get(counterState) * 2, });
Fetching Data with Selectors
Selectors can be used for asynchronous data fetching.
const asyncData = selector({ key: 'asyncData', get: async () => { const response = await fetch('https://api.example.com/data'); return response.json(); }, });
Atom Families
Atom families generate multiple atoms dynamically, useful for managing lists or dynamic data.
Using Atom Families
Atom Families allow the creation of dynamic atoms, useful for lists like todos.
import { atomFamily } from 'recoil'; const todoState = atomFamily({ key: 'todoState', default: (id) => ({ id, text: '', completed: false }), });
Selector Families
Selector Families enable derived state based on dynamic parameters, similar to atom families.
import { selectorFamily } from 'recoil'; const todoDetails = selectorFamily({ key: 'todoDetails', get: (id) => async () => { const response = await fetch(`https://api.example.com/todos/${id}`); return response.json(); }, });
RecoilRoot
Wrap the application with RecoilRoot to use the Recoil state.
import { RecoilRoot } from "recoil"; function App() { return ( <RecoilRoot> <MyComponent /> </RecoilRoot> ); }
Asynchronous State Management
Use selectors to handle async data with async/await.
import { selector } from "recoil"; const asyncData = selector({ key: "asyncData", get: async () => await fetchData(), });
State Persistence
Persist state using libraries like recoil-persist.
import { recoilPersist } from "recoil-persist"; const { persistAtom } = recoilPersist(); const myState = atom({ key: "myState", default: 0, effects_UNSTABLE: [persistAtom] });
Debugging Tools
Use Recoil DevTools to debug state changes.
Install the Recoil DevTools extension and wrap RecoilRoot in your app. No additional code changes are needed.
Performance Optimization
Use useRecoilCallback and efficient state splitting to avoid unnecessary re-renders.
import { useRecoilCallback } from "recoil"; const callback = useRecoilCallback(({ snapshot }) => () => console.log(snapshot.getLoadable(state)));