Simplifying State Management with Recoil in React

nishanthan-k
3 min readJul 9, 2024

--

Introduction

Recoil is a state management library for React applications. While there are several state management options available, such as Redux and Zustand, Recoil offers a unique and efficient way to manage state, especially in complex applications.

Recoil, An state management library

State Management in React

When building React applications, we often need to share state values between different components. There are two common methods to achieve this:

  1. Via Props: If components have a parent-child relationship, state can be passed through props. However, this method becomes impractical when the components are not directly related.
  2. Via useContext: This is a more flexible solution, but as the application grows, maintaining the codebase becomes challenging. Additionally, useContext can cause unnecessary re-renders in all components that consume the context, even if they don’t use the updated state.

State management libraries, like Recoil, address these issues by providing a global state that can be accessed anywhere in the application. They ensure components only re-render when the specific state they depend on is updated.

Creating State in Recoil

Recoil uses atoms and selectors to manage state.

Atom:

Similar to useState, atoms are the fundamental units of state in Recoil. They take two properties: key (which must be unique) and default (the initial state value).

import { atom } from 'recoil';

export const messageNotification = atom({
key: "messageNotification",
default: 0,
});

Selector:

Selectors derive state from other state values. They can compute state based on atoms or other selectors, making them ideal for creating derived state.

import { selector } from 'recoil';

export const totalNotificationCount = selector({
key: "totalNotificationCount",
get: ({ get }) => {
const messageNotification = get(messageNotification);
const followersNotification = get(followersNotification);
const postsActionNotification = get(postsActionNotification);

return messageNotification + followersNotification + postsActionNotification;
},
});

Basic Hooks in Recoil

useRecoilState:

This hook is used to get both the value and the setter function for an atom, similar to useState.

import { useRecoilState } from 'recoil';

const [messageNotification, setMessageNotification] = useRecoilState(messageNotification);

useRecoilValue:

This hook is used to get the value of an atom or selector. It’s useful when you only need to read the state.

import { useRecoilValue } from 'recoil';

const messageNotification = useRecoilValue(messageNotification);

useSetRecoilState:

This hook is used to get the setter function for an atom. It’s useful when you only need to update the state.

import { useSetRecoilState } from 'recoil';

const setMessageNotification = useSetRecoilState(messageNotification);

Advanced Concepts in Recoil

Asynchronous Data Queries:

When fetching state from a backend, Recoil can handle asynchronous operations using selectors. This prevents the UI from rendering blank spaces while waiting for data.

import { atom, selector } from 'recoil';
import axios from 'axios';

export const messageNotification = atom({
key: "messageNotification",
default: selector({
key: "messageNotificationSelector",
get: async () => {
const res = await axios.get('url');
return res.data;
},
}),
});

Conclusion

Recoil provides a powerful and flexible way to manage state in React applications. By understanding how to create and use atoms, selectors, and the various hooks, you can efficiently manage complex state and improve the performance and maintainability of your application.

--

--

nishanthan-k
nishanthan-k

Written by nishanthan-k

Data-driven professional with a passion for transforming complex information into insights. Expert in data analysis, visualization, and storytelling.

No responses yet