What's new in React 18? | #1 Automatic Batching
What is Batching?
Batching is when React groups multiple state updates into a single re-render for better performance. Hmm confused...
For example, if you have two state updates inside an event handler, React has always batched these so that there is only one re-render.
So in the above example the view is rendered only once if we click on the Next button.
Hmm... So React does automatic batching for us in case of event handlers (And mind you its React 17). Instead of triggering two different renders in case of a single click React is smart enough and batches these two re-renders into a single re-render. Thus improving app performance.
Now let's try to understand what was the issue with batching state updates in React till now.
React wasn’t consistent about when it batches updates. For example, if you need to fetch data, and then update the state in the handleClick above, then React would not batch the updates, and perform two independent updates. For Example:-
We are now updating state after we have fetched some data from a mock function which resolves after 100 ms. Now React would not batch the updates, and perform two independent updates.
So the automatic batching is what we want in above case as well instead of extra re-renders. As more re-renders leads to a bad user experience.
So the issue is that React only performs batched updates inside of an event handler callback and not when state updates in some other inner type of callback. Like a promise callback in above example.
So from React 18, React automatically batches the state updates which are not directly in event handlers or event callbacks.
How can we use React 18 today?
Its easy just go to terminal and type below commands:-
As soon as you go to browser to the running application you will get below waning:-
Enter New Root API
So to enjoy all of the React 18 goodies we will have to make some changes to the way we are rendering our root component.
So ReactDOM.render is deprecated from React 18. Instead we will have to use the new createRoot API instead as below:-
And now if we click the button there will only be a single render.
Sweet isn't it.
Now the question arises, what if we have to opt out of this default behaviour.
Enter flushSync to the rescue
So we have wrapped each state change in flushSync API to kind of force two different re-renders on each state change. And the result is as below after tapping on the button:-
TLDR; Until React 18, React only batched updates during the React event handlers. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default.
From React 18 using the new Root API, we get automatic Batched Updates even in the above excepted cases.
Be aware to not use React 18 yet for your Production apps as React 18 is still in alpha. But it is good to know what it brings to the table.
Hope you like this once. Till next time TaDa.
Take care and stay safe.