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

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay