Automatic Batching in React

Ramkumar Khubchandani
2 min readJan 11, 2024

--

Understanding Automatic Batching:

  • In React 18, state updates are automatically batched, regardless of where they originate from. This means React will group multiple state updates together and re-render the component only once, leading to performance improvements.
  • This applies to updates within event handlers, promises, timeouts, intervals, and other asynchronous events.

1. Setting Up a React 18 Project:

  • Create a new React project or upgrade an existing one to React 18:
npx create-react-app my-app --use-npm
cd my-app
npm install react@18 react-dom@18

2. Using createRoot() API:

  • Update your index.js file to use createRoot() for enabling React 18 features:
import React from

'react';
import ReactDOM from

'react-dom/client';
import App from

'./App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

3. Example with Timeout:

import React, { useState, useEffect } from 'react';

function MyComponent() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);

useEffect(() => {
// Simulating an asynchronous operation
setTimeout(() => {
setCount(count + 1);
setFlag(true);
}, 1000);
}, []);

return (
<div>
<p>Count: {count}</p>
<p>Flag: {flag.toString()}</p>
</div>
);
}

5. Observing Automatic Batching:

  • In this example, even though state updates happen within a timeout, React will batch them and re-render the component only once after the timeout.
  • You’ll see a single log message in the console indicating the re-render, proving that React batched the updates.

Key Points:

  • Automatic batching is enabled by default in React 18.
  • It applies to all state updates, including those within events, promises, timeouts, and intervals.
  • It leads to better performance by reducing unnecessary re-renders.
  • You can opt out of batching for specific updates using flushSync from react-dom.

Do you want to learn more like this ?

Follow me or message me on Linkedin.

--

--

Ramkumar Khubchandani
Ramkumar Khubchandani

Written by Ramkumar Khubchandani

Frontend Developer|Technical Content Writer|React|Angular|React-Native|Corporate Trainer|JavaScript|Trainer|Teacher| Mobile: 7709330265|ramkumarkhub@gmail.com

No responses yet