Automatic batching for better performance
Dhruvang Gajjar
Posted on May 2, 2023
What is batching?
Batching is when React groups multiple state updates into a single re-render for better performance.
React has always combined two state updates that occur inside the same click event into a single re-render. You can notice that React only renders once for each click even though the state was set twice if you execute the following code:
export default function App() {
const [count, setCount] = useState(1);
const [flag, setFlag] = useState(true);
function handleClick() {
setCount((count) => count + 1);
setFlag((flag) => !flag);
}
return (
<div className="App">
<h1>
{count} is {flag ? "odd" : "even"}
</h1>
<button onClick={handleClick}>Click</button>
</div>
);
}
What is automatic batching?
Starting in React 18 with createRoot, No matter where they come from, all changes will be automatically batched.
This means that updates inside of timeouts, promises, native event handlers or any other event will batch the same way as updates inside of React events
Also If you need to re-render the component, you can disable automatic batching by using flushSync
.
That's all about React batching.
If you want to discuss things related to Web Technology or want to explore more, You can always reach me out at dhruvangg@gmail.com OR Twitter
LinkedIN
Posted on May 2, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.