Recoil: Baby Steps
Atoms
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.
If the same atom is used from multiple components, all those components share their
state.
Atoms basically act like [Link] can subscribe to the state and update themselves.
const store = atom<number>({
key: 'store_key', // key should be unique.
default: 0,
});
const Comp = () => {
const state = useRecoilValue(store);
return <div>state: {state}</div>;
}
Recoil Subscribing Hooks
useRecoilState : like [Link] , 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
Selectors are pure functions that accept atoms or other selectors as input.
const priceSelector = selector({
key: 'priceSelector',
get: ({get}) => {
const bread = get(purchasedBreadAtom);
const beverage = get(purchasedBeverageAtom);
return (bread?.price || 0) + (beverage?.price || 0)
}
});
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.
AtomFamily
An atomFamily represents a collection of atoms. When you call atomFamily() it will return a
function which provides the RecoilState atom based on the parameters you pass in. The
atomFamily() essentially provides a map from the parameter to an atom. You only need to
provide a single key for the atom family and it will generate a unique key for each underlying
atom.
onst elementPositionStateFamily = atomFamily({
key: 'ElementPosition',
default: [0, 0],
});
const elementListItem = ({elementID}) => {
const position = useRecoilValue(elementPositionStateFamily(elementID));
return (
<div>
Element: {elementID}
Position: {position}
</div>
);
}
SelectorFamily
A selectorFamily is a powerful pattern that is similar to selector , but allows you to pass
parameters to the get and set callbacks of a selector . The selectorFamily() utility
returns a function which can be called with user-defined parameters and returns a selector.
const myNumberState = atom({
key: 'MyNumber',
default: 2,
});
const myMultipliedState = selectorFamily({
key: 'MyMultipliedNumber',
get: (multiplier) => ({get}) => {
return get(myNumberState) * multiplier;
},
});
const myComponent = () => {
// defaults to 2
const number = useRecoilValue(myNumberState);
// defaults to 200
const multipliedNumber = useRecoilValue(myMultipliedState(100));
return <div>...</div>;
}
What's Next?: [Link]