Sitemap
Abbas Roholamin

Abbas Roholamin

Batching in Reactjs

2 min readAug 26, 2024
Press enter or click to view image in full size

Batching in React refers to the process of grouping multiple state updates together into a single re-render, which can improve performance and efficiency. By default, React schedules updates and re-renders in a way that only the minimal necessary updates are made to the DOM. Batching helps ensure that when multiple state changes occur within a single event handler, they are processed in one go instead of causing multiple renders.

Get Abbas Roholamin’s stories in your inbox

Join Medium for free to get updates from this writer.

🎯 How Batching Works
✊ Event Handlers:
Most synchronous event handlers in React, such as those triggered by user interactions (e.g., clicks, form submissions), automatically batch state updates. This means if you call setState multiple times in a single event handler, React will only perform a single re-render.

const handleClick = () => { 
setCount(count + 1);
setValue("Updated");
// Only one re-render occurs here
};

🔃 Asynchronous Updates: In older versions of React, state updates inside promises or setTimeout were not batched, leading to multiple renders. However, with React 18 and onwards, asynchronous updates are batched by default when using the new concurrent features. For example:

const handleAsyncClick = async () => { 
setCount(count + 1);
setValue("Updated");
await new Promise((resolve) => setTimeout(resolve, 1000));
// Still only one re-render, thanks to new batching behavior
};

🎈 Functional Updates: When using functional updates (like setCount((prev) => prev + 1)), you can ensure that your state updates are based on the most recent state, even if multiple updates are batched.

🌲 Benefits of Batching
✈ Performance: Fewer re-renders lead to improved performance, as React makes fewer updates to the DOM.
📚 Consistency: When multiple state updates can cause cascading effects (where one update might depend on another), batching ensures that updates happen in a predictable manner.

🔗 Limitations
↖ In Direct State Updates: If you directly mutate state (which is against React’s best practices) or rely on outdated state values, batching may not have the desired effect, leading to bugs.
📤 Outside of React’s Scope: If a state update occurs outside of React’s controlled environment (e.g., inside a setInterval or a third-party library that interacts with DOM elements directly), batch updates won’t apply.

Conclusion
Batching is a fundamental optimization in React that helps to minimize unnecessary renders and maintain consistency in state management. Understanding how and when batching occurs can help developers write more efficient and performance-friendly React applications.

--

--