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:
Console Output:
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.
Console Output React 17:
Console Output React 18:
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!
Top comments (7)
Good explanation about React 18 auto batching!
Anyway, I think it would be better if you can update setState examples by using callbacks instead of referencing the current state value directly
Thank you,
Thanks very much! Great suggestion, I've updated the article. Appreciate it & all the best.
very nice ๐!
Hmm,
I haven't used React for a while,
I was under the impression that Auto Batching was already there in React 16
Interesting good to know this.
Yeah, it's been around for a little bit. But it wasn't applied in every situation, unfortunately. Seems like a nice improvement to me. Thanks for reading & the comment. Take care.
Nice topic
Thanks very much!