React 18 is coming up with Automatic Batching for fewer renders along with new other features like SSR support for Suspense.
Support for concurrent features will help in improving user experience.
Batching was present in React from the previous versions as well. But, with the introduction of Automatic Batching, there will be uniformity in the behaviour of re-rendering.
In React, components re-render if the value of state or props is altered.
State updates can be scheduled using setState in case of Class components.
In Functional components, state values can be updated using the function returned by useState.
React performs Batching while updating component state for performance improvement.
Batching means grouping multiple state updates into a single re-render.
Let us see how Batching used to work before v18 and what changes have been brought in v18.
Batching before React 18
React, by default performs batch updates only inside event-handlers.
So, setState is asynchronous only inside event handlers. But, synchronous inside of async functions like Promises, setTimeout
If n state updates were present in async functions, React re-renders component n number of times, updating one state per render.
However, forced batching can be implemented with the help of an unstable API ReactDOM.unstable_batchedUpdates
Note: The API is unstable in the sense that React might remove this API once uniformity is brought in the functionality of Batching
Batching in React 18
React 18 performs automatic batching with the help of createRoot API.
setState is asynchronous even inside async fucntions.
Batching will be done throughout the components similarly irrespective of its origin.
One can opt out of Batching with the help of ReactDOM.flushSync
ReactDOM.unstable_batchedUpdates API still exists in React 18, but it might be removed in the coming major versions.