Recoil

State Management which is more like React

State management has become a core part of any application development. The container pattern, helps us create a single source of truth for all the app’s data. Redux and MobX being the goto state management libraries, when it comes to React. They are opinionated(which is a plus) and need you to learn new patterns which are specific to them, which adds another step to the whole app building process.

  • Context can only store a single value, not an indefinite set of values each with its own consumers.

Core Concepts/Apis:

Atoms: each atom is a unit of state. They’re updateable and subscribable: when an atom is updated, each subscribed component is re-rendered with the new value. And the best part being they can be created at runtime. Atoms can technically replace component state and can be directly injected to components which are dependant on the state, rather than passing them as props.

import { atom } from 'recoil';const textState = atom({
key: 'textState', //identifier
default: '', // initial state});
import { useRecoilState } from 'recoil';
import { textState } from '../counter/Counter';
function TextInput() {
const [counter, setCounter] = useRecoilState(textState);
const onChange = (event) => {setCounter(event.target.value);};
return (
<div>
<input type='text' value={counter} onChange={onChange} placeholder='Enter text'/>
<h5>Input text: {counter}</h5>
</div>
);}
import { selector } from 'recoil';const charCountState = selector({
key: 'charCountState', // identifier
get: ({ get }) => {
const text = get(textState);
return text.length;
},
});
import { useRecoilValue } from 'recoil';const DisplayCount = () => {
const count = useRecoilValue(charCountState);
return <h5>Character Count: {count}</h5>;
};
Recoil core features example

A UI /UX Designer and JS Enthusiast, with a passion for travelling and writing.