What's Automatic Batching? React 18 feature explained

danstanhope

Dan Stanhope

Posted on March 31, 2022

What's Automatic Batching? React 18 feature explained

If you've ever built a component in React, chances are you've used state variables. If you've ever build a kinda-complex component in React, chances are you've got multiple state variables in use.

So, what happens when we update those variables? The component re-renders, right? Make changes to a bunch of state variables and a bunch of re-rendering happens. All this rendering could have performance implications for your app.

Introducing automatic batching. Now, batching has been around for a bit in React. But, React only automatically batched state changes for you if they were called inside a hook or browser event. Like say, a click event:

Image description

Console Output:

Image description

This is automatic batching. React takes multiple state changes and groups them together so they don't happen independently -- fantastic stuff.

So where's the improvement?

There are other places you may want to change state in your component(promises, timeouts). Let's say we have a component that fetches some data after a button click. We have two state variables, an array of users and a page counter. We want to update these inside a promise once the data is returned. In React 17, this will cause the component to re-render twice.

Image description

Console Output React 17:

Image description

Console Output React 18:

Image description

This is great! You can make changes to a couple state variables and React will apply them all at the same time, automatically, for you. Awesome!

If you weren't aware of how batching worked in previous versions of React, hopefully you know the limitations now. And if you've got some components out there changing state variables inside promises, might be time to upgrade :)

Thanks!

💖 💪 🙅 🚩
danstanhope
Dan Stanhope

Posted on March 31, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related