In React, automatic batching is a mechanism that groups multiple consecutive state updates or re-renders into a single update to improve performance by minimizing the number of DOM updates.

How Automatic Batching Works?

1. Event Handlers and React Updates

2. Batching Updates

Examples of Automatic Batching

Event Handler with Multiple State Updates.

function handleClick() {
  setState1(newState1);
  setState2(newState2);
  // Both state updates are batched and cause only a single re-render.
}

useEffect with Multiple State Changes.

useEffect(() => {
  setState1(newState1);
  setState2(newState2);
  // Both state updates inside useEffect are batched.
}, [dependency]);

Forces that Trigger Immediate Update

Controlling Batching Manually

ReactDOM.unstable_batchedUpdates(): React provides an unstable API ReactDOM.unstable_batchedUpdates() that you can use to manually batch multiple updates. This method is not recommended for general use as it's an unstable API.

Benefits

Performance Improvement: Reduces unnecessary re-renders and optimizes DOM updates, enhancing performance in React applications.

Conclusion

Automatic batching in React optimizes performance by grouping consecutive state updates within the same synchronous event or React flow, leading to fewer re-renders and more efficient DOM updates. This helps improve the overall performance of React applications by minimizing unnecessary rendering cycles.