DEV Community

Abhinav
Abhinav

Posted on

Batch Update in React

What is batch update?

Batching in React when React groups the multiple change is state are grouped into single update for better performance.

Every time we change the state React renders the components of the page.

Here in the given example we are changing the state 3 times but the render will happen only once.

import React from "react";
class App extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            name: '',
            likes: '',
            product: ''
        };
    }
    handleClick = () => {
        this.setState({
            name:"john",
        })
        this.setState({
            likes:"cricket",
        })
        this.setState({
            product:"bat"
        })

    }

    render() {
        console.log("rendering");

        return (
            <div className="App">
                <div>
                    <button onClick={this.handleClick}>Next</button>
                </div>
            </div>
        );
    }
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Image description

What happens here is when we press the button the state is changed using this.setSate and react batches the all of these changes and renders it one go.

In earlier versions of React, batching was only done for the event handlers.

React v18 ensures that state updates made from any location are batched by default. This will batch state updates, including native event handlers, asynchronous operations, timeouts, and intervals.

Here in this example if we for React v17 React will change the state of the components we by on and hence when we console.log(this.state) see the React 17 : { counter1: 1, counter2: 0 } because the state has been and rendered for the the first state change.

import React from "react";
class App extends React.Component {
    state = {
        counter1: 0,
        counter2: 0
    }

    handleClick = () => {
        setTimeout(() => {
            this.setState(({ counter1 }) => ({ counter1: counter1 + 1 }));
            console.log(this.state);
            //React 17 : { counter1: 1, counter2: 0 }
            //React 18 with createRoot : { counter1: 0, counter2: 0 } 
            this.setState(({ counter2 }) => ({ counter2: counter2 + 1 }));
        });
    };

    render() {
        console.log('Rerendered');
        console.log(this.state);
        // {counter1: 1, counter2: 1}
        return (
            <div className='App'>
                <button onClick={this.handleClick}>Click me</button>
            </div>
        )
    }
}

export default App;

Enter fullscreen mode Exit fullscreen mode

In react v18
Image description

References

Top comments (0)