What is Recoil?
Recoil is a state management library for React applications. As React applications are typically developed using its component-based architecture, we frequently encounter the need to share data or values between components. Recoil simplifies this process by utilizing fewer lines of code and maintaining a minimalist structure.
Features
In most web applications, we do not require heavy state management tools with complex structures. However, we often find tools with simple structures and minimal code requirements. In this case, Recoil is a suitable option. However, if you are working on large and complex data applications, Redux will be a better choice.
Features | Recoil |
Usability | Only for React.js applications |
Architecture | Atom based state management. |
State Structure | Decentralized |
Boilerplate | Minimal setup required |
Why Use Recoil?
1. If you are developing React.js or Next.js projects and require a lightweight state management solution, Recoil may be the suitable choice.
2. Additionally, if you do not need a complex code structure and your state primarily resides within local components, Recoil can simplify your development process.
Installation
There are a few things that will be used in this process that are:
> RecoilRoot
> atom
> selector
> useRecoilState
> useRecoilValue
RecoilRoot
RecoilRoot itself is the store which helps to exchange the state throughout the application. There is no need to pass extra parameters here.
Code
We will create separate folder to store recoil files
Recoil
> atom.tsx
> provider.tsx
> selector.tsx
Atom
An atom represents a piece of state. Atoms can be read from and written to from any component. Simply mean If we change value of atom in any components then it will applicable to all the component where the atom is being used.
atom.tsx
key : unique key is required for every atom
default: Default values can be set here to use it before the state changes.
Warning - Note that one key shouldn’t be repeat for atoms and selectors throughout the application.
Selector
A selector represents a piece of derived state. Derived state is a transformation of state. If you want to make changes in upcoming values or the data then you can do it in this section
selector.tsx
For React.js App
For Next.js app
Since Next.js has server-side rendering (SSR), Recoil should be initialized in the client-side components.
provider.tsx
We have few repeated components like Header, any popups, Menus, footer etc. So we can create Separate Recoil provider and will pass children’s over there rather than layout.tsx
#Important Note: If you have installed Recoil and encountered issues with its functionality, it is possible that your React.js version is incompatible. To resolve this, you can consider installing previous versions of Recoil. For instance, if you are experiencing problems with Recoil version 7.7, you can try version 7.5.