If I have to set states from multiple different atoms as part of some high level action user is taking, I want all subscribing components for any of the impacted atoms to be re-rendered only once when the entire states are set as a batch. Is this possible with Recoil?
Asked
Active
Viewed 1,147 times
1 Answers
1
Recoil batches the state updates by default (this is also true for React state itself). If you don't want to batch the updates code wise, you could use the useRecoilCallback
hook, something like this:
const Component = () => {
const batchUpdates = useRecoilCallback(({set}) => (valueA, valueB) => {
set(atomA, valueA);
set(atomB, valueB);
}, []);
return (
<button onClick={() => batchUpdates(someValueA, someValueB)}>Batch Updates</button>
);
};

Johannes Klauß
- 10,676
- 16
- 68
- 122
-
1It's worth noting that the updates are batched as long as they are performed synchronously. If you do something like `set(a, await reqA()); set(b, await reqB())` then the updates will not batch. – pumbo Jun 06 '21 at 04:53