DEV Community

Sachin
Sachin

Posted on

Batch Update

In react 17 version, when we set multiple state in this.state .
render can run for each state when update . so , its can effect performance while working.

But after react 18 version, render can run once after all state updated.
below this code is example of render,

import React from "react";
import "./styles.css";

class batch extends React.Component {
  constructor() {
    super();
    this.state = {
      increment1: 0,
      increment2: 0
    };
  }

  bottonClick = () => {
    this.setState({
      increment1: this.state.increment1 + 1,
      increment2: this.state.increment2 + 2
    });
    console.log("render");

  };

  render() {
    return (
      <>
        <h1> batch update</h1>
        <div>increment1 : {this.state.increment1}</div>
        <div> increment2 : {this.state.increment2}</div>
        <button onClick={this.bottonClick}> increment</button>
      </>
    );
  }
}
export default batch;
Enter fullscreen mode Exit fullscreen mode

Advantage

Separate changes to the state(increment1 and increment2) within the event handler (bottonClick) will result in single rendering

Disadvantage

But it doesn't work in every situation.
when an event handler that uses asynchronous operation then separate state updates will not be batched.

Image description

Helping links :
medium
and
log rocket

Top comments (0)