[JSByte by Shruti Kapoor] What is Automatic Batching in React 18?
React 18 introduces Automatic Batching. Automatic Batching is the process by which React batches state updates that happen in a "micro-task" in a single state cycle. Previously, React batched state updates that happened in a single event callback managed by React system, however state updates that happened within timeouts, promises, or native event handlers were not batched. Here is an example that explains it -
Previously, these three would lead to separate renders - 3 in total. With the help of automatic batching now, these will instead lead to single render - 1 in total.
Dan Abramov explains in simple words on React Working Group's thread - it is like going to a grocery store "on demand" when you are cooking something. Let's say you are making breakfast - you start cooking, realize you don't have eggs, so you go to the store and buy eggs, come back and resume cooking. Then you realize you don't have coffee so you go to the store and buy it and resume cooking. Clearly this is not effective. So you make a grocery list, go to the store and buy everything you need in one go. This is automatic batching.
It is available out of the box, but can be opted out by using flushSync.
Read more about Automatic Batching in this GitHub discussion thread.
On a personal note
Last week I am recorded my conference talk for the official React Conf where I will be talking about React 18 for App Developers. You can sign up for the conference here. Hope to see you there!
Check out this giant recording equipment that came in mail this week.