DEV Community

Balraj Jha Anand
Balraj Jha Anand

Posted on

Batched updates in react

What are batched updates in react

To put it simply, for better performance react is going to combine multiple state updates into a single state update.

So for e.g. if you have multiple setState inside of the same click event then react is going to cause a render only once and combine all those state updates into a single update which will cause the render.

This may come as a surprise as we previously know that react causes a render whenever it encounters a setChange method.

What do you think will be the output of the code below in the console after the button is clicked?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
      flag: false,
    }
  }

  handleButtonClick = (event) => {
    console.log("Button clicked");

    this.setState({
      counter: this.state.counter + 1,
    });

    this.setState({
      flag: !this.state.flag,
    });
  }

  render() {
    return (
      <>
        <h1>{`Counter: ${this.state.counter}`}</h1>
        <h1>{`Flag: ${this.state.flag}`}</h1>

        <button onClick={this.handleButtonClick}>Click me</button>

        {console.log("render")}
      </>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Let's walk through the above example:

I'm making a class component called App and inside it, there are two values that are getting initialized inside the constructor: counter and flag. I will change these values whenever the button is clicked through the onClick event by passing in handleButtonClick function. This function will update the state of the counter and flag but it calls setState twice.

What you might expect to happen:

Firstly, "render" is output once due to the initial render. Then when the button is clicked "render" will be output twice because you called setState twice.

What actually happens:

Same initial "render" output, but when the button is clicked, "render" is output only once to the console. This shows us that react batches multiple state into a single update which causes the render.

Hope you now understand what batched updates are in React. If you find any mistakes here kindly let me know in the comments.

Top comments (0)