What is Automatic Batching in React? | Benefits & Implementation

React is a well-known open-source JavaScript library for creating user interfaces. It provides a simple as well as efficient method for managing your application’s state and updating the DOM (Document Object Model) in response to changes in that state.

When multiple state updates are grouped as one re-render update in React, it is referred to as Batching in React. Batching is done to improve application performance; however, in previous versions of React, batching was only done within React event handlers.

This has been improved in React 18, where all states update regardless of where they are batched. This is known as Automatic Batching.

 In this article, we will explore what automatic batching is, how it works & how it can help your React applications perform better.

What is Automatic Batching?

You can use automatic batching to call the state update function multiple times in a short period of time. This is because React does not update the DOM until all states have been processed. React can now perform a single re-render for all updates, including updates inside Promises, SetTimeOut, native event handlers & any other events, which was not possible in previous React versions.

How does automatic batching work?

Automatic batching works by delaying a component’s re-rendering until all state updates have been processed. React adds a state update to a queue of pending updates when it is triggered. If another state update is triggered before React has finished processing the pending updates, it is added to the queue as well.

React processes all pending updates in the order they were added to the queue once it is ready to update the DOM. This means that all state updates triggered within a single event loop will be grouped together and processed as a single update.

Let’s take a look at an example to see how this works in practice.

import { useState } from 'react';
import './App.css';

function App() {
  const [counterPlus, setCounterPlus] = useState(0);
    const [counterMinus, setCounterMinus]=useState(0);
    const handleClick=()=>{
      setCounterPlus(counterPlus +1);
      setCounterMinus(counterMinus-1);
    }
    console.log("Rendered Components", counterPlus, counterMinus);
  return (
    <div className="Container">
      <header className="Header-content">
        
        <p>
         Automatic Batching Example
        </p>
        <button
          className="Btn-red"
        onClick={()=>{
          handleClick();
        }}
      >
          Click Here
        </button>
        <div>Add Count:{counterPlus}</div>
        <div>Minus Count:{counterMinus}</div>
        
      </header>
    </div>
  );
}
export default App;

In the above code snippet, we have two state variables. One for the added counter, and another for the removed count. handleClick is a function that modifies the two state variables. When this component renders, we want to log out the rendered components, followed by the number of counts added and subtracted, which is why we use console.log. For the user interface, we have a button with a click event that is wired to the handleClick() function and displays the count added and count removed.

Below is what the UI looks like.

automatic batching in react

Now, let’s inspecting web elements in a browser to debug page or check website appearance or JavaScript code behavior.

automatic batching

Both counterPlus and counterMinus are zero the first time the component is rendered. The component re-renders only after both state changes have been committed, as a result of automatic batching; even though two state variables are changing, we only get a single re-render, as shown below.

automatic batching in JS

How to Control Automatic Batching?

Although automatic batching is a useful feature, you may not want to use it all of the time. To manage this feature, in react-dom, there is a method called flushSync() that allows us to re-render for a specific state update.

import { flushSync } from 'react-dom';

Call the method inside the handle click function and put your state variable inside the flushSync body as shown below.

const handleClick=()=>{
      flushSync(() => {
        setCounterPlus(counterPlus +1);
      })
      
      setCounterMinus(counterMinus-1);
    }

When the click event is triggered, React will update the DOM once with flushSync() and again with setCounterMinus(counterMinus-1), avoiding automatic batching as seen below:

Control Automatic Batching

The Final Overview: Automatic Batching in React

Automatic batching in React is a roboust feature that allows for efficient user interface updates by grouping multiple state changes into a single update. Instead of rendering each change as it happens, React waits until a batch of updates is complete before re-rendering the component tree.

It results in improved performance and fewer unnecessary re-renders, which can have a significant impact on an application’s speed and responsiveness. Automatic batching is a critical component of React’s rendering engine that can be used to improve the performance of even the most complex web applications.

Understanding how automatic batching works allows developers to create more efficient and responsive user interfaces capable of meeting the demands of modern web development.

Stay in the Loop

Get the weekly email from Algoideas that makes reading the AI/ML stuff instructive. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement -

You might also like...