DEV Community

Cover image for Automatic batching for better performance
Dhruvang Gajjar
Dhruvang Gajjar

Posted on

1

Automatic batching for better performance

What is batching?

Batching is when React groups multiple state updates into a single re-render for better performance.

React has always combined two state updates that occur inside the same click event into a single re-render. You can notice that React only renders once for each click even though the state was set twice if you execute the following code:

export default function App() {
  const [count, setCount] = useState(1);
  const [flag, setFlag] = useState(true);

  function handleClick() {
    setCount((count) => count + 1);
    setFlag((flag) => !flag);
  }

  return (
    <div className="App">
      <h1>
        {count} is {flag ? "odd" : "even"}
      </h1>
      <button onClick={handleClick}>Click</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

What is automatic batching?

Starting in React 18 with createRoot, No matter where they come from, all changes will be automatically batched.

This means that updates inside of timeouts, promises, native event handlers or any other event will batch the same way as updates inside of React events

Also If you need to re-render the component, you can disable automatic batching by using flushSync.

Use flushsync to opt-out automatic batching

That's all about React batching.

If you want to discuss things related to Web Technology or want to explore more, You can always reach me out at dhruvangg@gmail.com OR Twitter
LinkedIN

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay