Recoil 2
Recoil 2
Recoil 2
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 storage.Components can subscribe to the state and update themselves.
useSetRecoilState : only returns setter and it won’t subscribe update of the state change.
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.
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,
});
// defaults to 200
const multipliedNumber = useRecoilValue(myMultipliedState(100));
return <div>...</div>;
}