Batching in React Before React 18
In earlier versions of React, batching was primarily limited to state updates that occurred within React event handlers. Consider the following code example:
Here’s a simple example:
function handleClick() {
setCount(count + 1); // Update 1
setIsVisible(true); // Update 2
}
React would intelligently recognize that these updates occur within the same event handler and batch them together, resulting in a single re-render of the relevant component.
However, state updates originating outside of event handlers, such as updates within promises, timeouts, or native event listeners, would not be batched by default. Let’s illustrate this:
setTimeout(() => {
setCount(count + 1); // Update 1
setIsVisible(false); // Update 2
}, 1000);
In React 17 and prior, this code could potentially trigger two separate re-renders, which might become a performance bottleneck in applications with frequent asynchronous updates.
What is Automatic Batching in React 18
React 18 includes great features including automatic batching, which enhances rendering effectiveness and results in significant gains for programmers and users.
This article is going to explain what batching is, how it worked before in React, and how our lives have been changed by automatic batching.
Table of Content
- What is Batching?
- Batching in React Before React 18
- What is Automatic Batching in React 18?
- Benefits of Automatic Batching
- Automatic Batching in Action
- When Automatic Batching Might Not Apply
- Advanced Use Cases and Best Practices
- Conclusion