Batch Updates in React 17 or Earlier Versions

React batch updates for multiple setState() calls inside setTimeout, promises, and native event handlers

--

Photo by Julian Hochgesang on Unsplash

TLDR; If you are on React 18, then you don’’t need to worry about batch updates, because with React 18 batch updates functionality comes pre-built in. But if you are using React 17 or earlier versions then you might need to see this.

With that said, let’s dive in learning about batch updates.

What is batch updates?

A feature or functionality of React which batches multiple state update calls into one update, and render the UI only once with the updated data.

React does this for us in case of Synthetic Events and in case of hooks as well, until and unless we aren’t calling state updates inside any async function.

Here is the demonstration of it:

Batch updates under synthetic events

Batch Updates under hooks:

However React does not batch updates when setState calls are made in any async methods or inside any native event handlers

Native event handler means any event this is added using addEventListener method.

1. No Batch Update under setTimeOut

each setState will render the component

2. No Batch Update under promises

each setState will render the component

3. No Batch Update in native event handlers

each setState will render the component

So how does we can achieve batch updates in all above cases?

For such cases unstable_batchedUpdates comes to the rescue. This was added as an experimental feature. But it does the job.

unstable_batchedUpdates is function, which can be imported from react-dom and it takes a callback function. Inside the callback function we can do call multiple state updates, which are batched at the end.

And simply call this function inside setTimeout, promises, native event handles and inside hooks

import { unstable_batchedUpdates } from "react-dom";setTimeout(()=> {    unstable_batchedUpdates(() => {            setCountOne((c) => c + 1);            setCountTwo((c) => c + 1);            // All other state updates, which will be clubbed into   one.     });
},0)

batching multiple set state calls inside setTimeout

batching multiple setState calls inside promise

batching multiple set state calls inside native event handlers

use unstable_batchedUpdates wisely, because as per Dan Abramov this is an unstable API.
But IMO for some cases, we can use this as if this is exposed to use, then I don’t think it will create much trouble.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord. Interested in Growth Hacking? Check out Circuit.

--

--