Batched Updates in React
Demonstrate how React batches multiple `setState` calls into a single update for performance optimization.
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
increment = () => {
// Below are two state update calls that React will batch together
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
In this code snippet, we have a React class component with a 'count' state. The 'increment' method has two consecutive 'setState' calls. React will automatically batch these updates into a single re-render for performance optimization. Clicking the 'Increment' button will only increment the count by 1 due to the batching effect.