Skip to main content

Recoil in React

Recoil is a lightweight state management library for React that provides a simple way to manage shared state across components. In this tutorial, we'll learn how to set up Recoil in a React app, create atoms, and use selectors to derive state.

Installing Recoil

First, let's install the Recoil package:

npm install recoil

Creating Atoms

Atoms are the basic building blocks of state in Recoil. They represent a single piece of state, and any component that uses an atom will automatically re-render when the atom's value changes.

JavaScript
import { atom } from 'recoil';

export const counterState = atom({
key: 'counterState',
default: 0,
});

In this example, we've created a simple counter atom with an initial value of 0.

Using Atoms in Components

Now let's create a Counter component that uses the counterState atom:

JavaScript
import React from 'react';
import { useRecoilState } from 'recoil';
import { counterState } from './counterState';

const Counter = () => {
const [count, setCount] = useRecoilState(counterState);

const increment = () => {
setCount(count + 1);
};

const decrement = () => {
setCount(count - 1);
};

return (
<div>
<h1>{count}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
};

export default Counter;

In this example, we've used the useRecoilState hook to access and update the counterState atom.

Creating Selectors

Selectors are pure functions that compute derived state based on other atoms or selectors. They can be used to perform calculations or transformations on state.

JavaScript
import { selector } from 'recoil';
import { counterState } from './counterState';

export const doubledCounterState = selector({
key: 'doubledCounterState',
get: ({ get }) => {
const count = get(counterState);
return count * 2;
},
});

In this example, we've created a selector that calculates the doubled value of the counterState atom.

Using Selectors in Components

Now let's create a DoubledCounter component that uses the doubledCounterState selector:

JavaScript
import React from 'react';
import { useRecoilValue } from 'recoil';
import { doubledCounterState } from './doubledCounterState';

const DoubledCounter = () => {
const doubledCount = useRecoilValue(doubledCounterState);

return <h1>Doubled count: {doubledCount}</h1>;
};

export default DoubledCounter;

In this example, we've used the useRecoilValue hook to access the derived state from the doubledCounterState selector.

Conclusion

In this tutorial, we've learned how to use Recoil for state management in React applications. We've set up atoms and selectors to manage and derive state, and connected our React components to the Recoil state using hooks.

Recoil provides a simple and efficient way to manage shared state across components, resulting in better performance and maintainability of your application.