DEV Community

Mohamed Idris
Mohamed Idris

Posted on

React Automatic Batching: How Many Re-renders?

Automatic Batching in React: How Many Re-renders?

Consider the following example:

import { useState } from 'react';

const App = () => {
  const [name, setName] = useState('');
  const [age, setAge] = useState(null);
  const [hobby, setHobby] = useState('');

  const displayPerson = () => {
    setName('Luiji');
    setAge(29);
    setHobby('swimming');
  };

  console.log('Component rendered');

  return (
    <>
      <h3>{name}</h3>
      <h3>{age}</h3>
      <h4>Enjoys: {hobby}</h4>
      <button className='btn' onClick={displayPerson}>
        {name === 'Yoshi' ? 'Display Person' : 'Person Displayed'}
      </button>
    </>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

When you click the button, how many times will the component re-render—1 or 3?

If you guessed 1, you're correct! This is because of React’s automatic batching.

Note: The first console.log is for the initial render, and the second is for the re-render triggered by clicking the button.


What is Batching?

In React, batching refers to the process of grouping multiple state updates into a single update to optimize rendering. Auto-batching is enabled by default in React, meaning when multiple state updates happen in the same event loop (like during a button click), React will batch them together and trigger only one re-render.


React 18 and Automatic Batching

With React 18, auto-batching is enabled by default, and it batches all state updates, including those from:

  • Native event handlers
  • Asynchronous operations (e.g., promises)
  • Timeouts and intervals

This optimization reduces unnecessary re-renders, leading to better performance.

Top comments (0)