State management is always the biggest concern for any developer specially in case of global state management. Recently, our beloved Facebook have launched a new state management library called Recoil. In this article we gonna see what features this new Library is offering.
What is Recoil ?
Recoil is a new state management library recently released by Facebook. Recoil is created by the same Creator who created the React. So, internally Recoil works as the same way as React works. Its fast and flexible shared state.
This new library specially designed to work with Pure functions. It also have few features similar to Redux like undo operation, time-travel debugging, routing etc.
How to use Recoil ?
First of all we need to install Recoil like any other package.
npm install recoil --save
Our Recoil library uses 5 different functions to perform state managment.
RecoilRoot
To use the Recoil state in the project first of all we need to wrap our app using this RecoilRoot Component.
import React from 'react';
import {
RecoilRoot,
} from 'recoil';
function App() {
return (
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>
);
}
Atom
The term atom represents a piece of state. Any component can read atom and also can update them. Once the value of an atom changes subscribed components will re render.
import {
atom
} from 'recoil';
const textState = atom({
key: 'textState', // unique ID (with respect to other atoms/selectors)
default: '', // default value (aka initial value)
});
useRecoilState
As the name suggest to use Recoil state we need to use useRecoilState function similar to useState.
import {
useRecoilState
} from 'recoil';
function TextInput() {
const [text, setText] = useRecoilState(textState);
const onChange = (event) => {
setText(event.target.value);
};
return (
<div>
<input type="text" value={text} onChange={onChange} />
<br />
Echo: {text}
</div>
);
}
Selector
A selector represents a piece of derived state. Here derived state means modification of a state by a normal function.
import {
selector
} from 'recoil';
const charCountState = selector({
key: 'charCountState', // unique ID (with respect to other atoms/selectors)
get: ({get}) => {
const text = get(textState);
return text.length;
},
});
useRecoilValue
To read the value of a selector we need to use useRecoilValue.
function CharacterCount() {
const count = useRecoilValue(charCountState);
return <>Character Count: {count}</>;
}
Top comments (2)
Thanks it's an interesting new feature.
Hint to dev.to writing -> You can use word
javascript
after three backticks ` to highlight your syntax :)Thanks for sharing I actually like the ideas around this new React state management