What is automatic batching in React?

Automatic batching includes batching state updates in a non-event handler function. It happens such that only one re-render is required instead of several re-renders for each state update.

Note: In React 18, automatic batching is enabled.

The ReactDOM.createRoot API is used in React 18 to batch all state updates automatically.

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();

Example

Consider the following example for updating a state in the React component:

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

function App() {
  const [count,setCount]=useState(0);
  const [toggle,setToggle]=useState(false);
  
  const handleClick = () => {
    setTimeout(() => {
      setCount(count => count+1);
      setToggle(toggle => !toggle);

    },10);
    
  };
console.log("Rendered",count,toggle)

    return (
        <div className="App">
        <button onClick={handleClick}> Click Me  </button>
        <div> Count: {count} </div>
        <div> Toggle :{toggle.toString()} </div>
 

        </div>
    );
  }
export default App;
React app with count and toggle functionality

Explanation

  • Lines 5–6: We create a basic React component with two state variables: one for storing a count, and the other for storing a toggle between true and false.

  • Lines 8–15: We create the handleClick function to modify the two state variables. When this component renders, it is followed by a count and the toggle value for the UI component.

  • Line 20: We create a button that, on click, is connected to the handleClick function and shows the count and the current toggle value.

  • Line 16: We print the number of renderers on the console. After clicking the Run button, navigate to the link next to “Your app can be found at:”. Now, to view the number of re-renders, right-click the window, select inspect, and then click the Console tab in the window on the screen’s right side.

When the component first renders, the count is zero, and the toggle is false, but when the button is clicked, the count is updated using setcount, and the toggle is updated with settoggle.

Due to automated batching, the component only re-renders when both of these state changes have been committed. React combines several state updates into a single re-render for optimal efficiency. React performs a single re-render after each click, even if two state variables change.

Avoid automatic batching

In react-dom, a method called flushSync() allows us to force a re-render for a specific state update. Here’s an example of how to use flushSync() to force a re-render for a specific update:

const handleClick = () => {
flushSync(() => {
setCount(count => count+1);
});
setToggle(toggle => !toggle);
};

In the code above:

  • Lines 3 and 5: React will make a re-render. When the event is triggered, React will update the DOM twice: once with flushSync() and again with setCount(count + 1), avoiding batching.

Conclusion

React 18 batches the updates, whether it’s a primary function with numerous state updates or a web API with interfaces like setTimeout, fetch, or a promise with multiple state updates. React 18 bridges the gap and increases application performance by minimizing the number of unwanted re-renders.

Copyright ©2024 Educative, Inc. All rights reserved