This content originally appeared on Bits and Pieces - Medium and was authored by kelly woo
An Introduction to Recoil: a React State Library
Getting Started
Docs: https://recoiljs.org/docs/introduction/getting-started#recoilroot
What caught my eyes is how easy it is to get started with Recoil. No configuration, no complicated implementation, you just wrap your app with RootRecoil, that’s it:
const App = ()=> {
return (
<RootRecoil>
<div id="app-started">
....
</div>
</RootRecoil>
);
}
Atoms
Docs: https://recoiljs.org/docs/introduction/core-concepts
Atoms are units of state. They’re updatable and can be subscribed to. When an atom is updated, each subscribed component is re-rendered with the new value. They can be created at runtime, too. Atoms can be used in place of React local component state. If the same atom is used from multiple components, all those components share their state.
atom can be used like storage, similar to React.useState(). Components can subscribe to the state and update themselves. It takes a key and a default value to create.
The key must be unique throughout the app. By default, the state of atom is immutable.
If mutation is intended, you can put the flag dangerouslyAllowMutability: true:
const store = atom<number>({
key: 'global store', // key should be unique.
default: 0,
// dangerouslyAllowMutability: false | true
});
const Comp = () => {
const state = useRecoilValue(store);
return <div>state: {state}</div>;
}
Subscribing methods(hooks) are the following:
- useRecoilState: like useState, it returns array with state and setter.
- useRecoilValue: returns state only.
- useSetRecoilState: only returns setter and it won’t subscribe update of the state change.
- useResetRecoilState: same as setRecoil but it sets back to initial state.

Selectors
Docs: https://recoiljs.org/docs/api-reference/core/selector
selector is a pure function that accepts atoms or other selectors as input. This is pretty much similar to Vue.js, which registers the dependency when it is called. Selector caches all the values by input. ‘Is’ comparison, same input, same output. It is all about memoization, preventing tree from rendering.
const priceSelector = selector({
key: 'priceSelector',
get: ({get, getCallback}) => {
const bread = get(purchasedBreadAtom);
const beverage = get(purchasedBeverageAtom);
return (bread?.price || 0) + (beverage?.price || 0)
}
});
get
The method to register dependency and read state to use. priceSelector gets value of purchasedBread & purchasedBeverage and when they change, priceSelector get notified and updates the subscribers.
getCallback
Your component does not need to re-render every time you grab a glimpse of the state. With getCallback, you can avoid re-rendering by peeking at them, the callback provides snapshot, like the menu and receipt from the following example.
Customer choose Menu from Menu component and Receipt component does not need updating of all the changes, it only needs then when it prints.
This is where we can use getCallback.
Snapshot should call with getPromise to avoid any action on render-time.
...
get: ({getCallback})=> {
const onClick = getCallback(({ snapshot }) =>
async (setPrice) => {
const menu = await snapshot.getPromise(menuAtom);
const purchased = await snapshot.getPromise(purchasedAtom);
setPrice(...);
})
return { onClick }
},
...
cachePolicy_UNSTABLE
What you should remember is selector is currently by default, memoizes all the values by input. In the example foodSelector gets food name and creates new instance with producedAt time.
const createFood: (n: string) => Food = (name: string) => {
return { name, producedAt: Date.now() };
};
const foodNameAtom = atom({... default: 'milk'})
const foodSelector = selector({
return createFood(get(foodNameAtom));
})
State change of the originate atom (which has string value of food name).

producedAt does not renew how many times you click new! It only provides with old one from the cache.
If you meant to keep it for the last one only, add the flag to the selector.
cachePolicy_UNSTABLE: {eviction: 'most-recent'},
// default is 'keep-all' .... why????

Now it memoizes the last one only and we get served with newly produced food.
Docs: https://recoiljs.org/docs/api-reference/core/selector#cache-policy-configuration
Surprisingly selector supports set method.
I wouldn’t explain it in details, because I’d rather update atom directly than through selectors (but in case of multiple atoms to be updated, it is useful).
Before setting the value you should check that the value is instanceof DefaultValue. This is to distinguish the value whether it is provided by resetting the value or not.
set: ({set}, newValue)=> {
if(newValue instanceof DefaultValue) {
....
} else {
....
}
}
See the example below:
======================================
Summary
Recoil is a fascinating library with an easy learning curve. Getting to gribs with selectors are a bit tricky, I didn’t write it here but selector supports async function for get method.
Async process makes everything complicated and complex, Recoil also provides loadable and all the utils like waitForNow, waitForAll etc.
For me, getCallback snapshot and global useState(atom) is quite fun and useful with light concepts, very satisfying, but whole selector thing is still not familiar.
I haven’t found the right or best way to cancel async process in selectors, have great expectation that recoil developers are working on it. Anyone has a better way to handle async and cancelling, please share it with me.
I hope this article help you to reach recoil easily. Let’s keep on loadable and other stuff next article. Happy coding!
Build modular, reusable React components with Bit.
Monorepos are a great way to speed up and scale app development, with independent deployments, decoupled codebases, and autonomous teams.
Bit offers a great developer experience for building component-driven monorepos. Build components, collaborate, and compose applications that scale. Our GitHub has over 14.5k stars!

Learn more
- Building a React Component Library — The Right Way
- 7 Tools for Faster Frontend Development in 2022
- Microservices are Dead — Long Live Miniservices
Getting Started with React Recoil was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by kelly woo

kelly woo | Sciencx (2022-01-14T18:41:19+00:00) Getting Started with React Recoil. Retrieved from https://www.scien.cx/2022/01/14/getting-started-with-react-recoil/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.