How many times will multiple setStates in React be called?

How many times will multiple setStates in React be called?

1. Two setState, how many times to call?

As shown in the following code, there is a count in state . A click event is bound to the button, and setState is executed twice in the event, increasing the value of count by 1 each time.

When a button is clicked, how many times will setState be executed? How many times will render() be executed?

Answer: 1 time each.

state = { count: 0 };
handleClick = () => {
    this.setState({ count: this.state.count + 1 });
    this.setState({ count: this.state.count + 1 });
};
render() {
    console.log(`render`);
    return (
        <>
            <div>Current count: {this.state.count}</div>
            <button onClick={this.handleClick}>add</button>
        </>
    );
}

According to common sense, when the button is clicked for the first time, since setState is executed twice, the value of count is increased by 1 each time, render() should be executed twice, and the final value of count should be 2. But that's not how React works.

Just run the above code in your browser:

At the beginning, the page shows that the value of count is 0 , and the console prints render , which is printed when React renders for the first time. After clicking the button, the page shows that count value is 1 , and only 1 render is printed, which means that React only executed setState once and render() once during this process.

The reason is that React internally merges multiple setState in the same event response function , reducing the number of setState calls, which can also reduce the number of renderings and improve performance.

This also explains why the final value of count in the above code is 1 , because React merged the two setState and only executed them 1 in the end, render() was also only executed once.

2. Two setState, which one is called?

But the above code does not verify which setState is executed after React is merged. As shown in the following code, change the operation on count in the second setState to add 2 , and keep the rest of the code unchanged:

state = { count: 0 };
handleClick = () => {
    this.setState({ count: this.state.count + 1 });
    this.setState({ count: this.state.count + 2 }); //Change to +2
};
render() {
    console.log(`render`);
    return (
        <>
            <div>Current count: {this.state.count}</div>
            <button onClick={this.handleClick}>add</button>
        </>
    );
}

Run it in the browser again:

The results show that after clicking the button, the value of count finally becomes 2 , which means that a +2 operation is performed, and render() is only executed 1 . This means that when React merges multiple setState , if there are attributes with the same name, the latter attribute with the same name will overwrite the former attribute with the same name . It can be understood that for attributes with the same name, the attributes in the last setState are ultimately executed.

3. Two setStates are placed in setTimeout?

If we add a timer setTimeout in the click event function and execute the setState operation twice in the timer, what will be the result? In the following code, a timer setTimeout is written in the event processing function, and two setState are put into setTimeout .

state = { count: 0 };
handleClick = () => {
    setTimeout(() => {
        this.setState({ count: this.state.count + 1 });
        this.setState({ count: this.state.count + 2 });
    }, 0);
};
render() {
    console.log(`render`);
    return (
        <>
            <div>Current count: {this.state.count}</div>
            <button onClick={this.handleClick}>add</button>
        </>
    );
}

Running results:

The results show that after clicking the button, the value of count finally becomes 3 , which means that both +1 and +2 operations are executed, render() is also executed 2 .

This is because calling setState directly in React's synthetic events and lifecycle functions will be managed by React's performance optimization mechanism , which will merge multiple setState . Calling setState in native events and setTimeout is not managed by React, so multiple setState will not be merged. If setState is written several times, setState will be called several times.

4. Conclusion

Events used directly in React, such as onChange and onClick , are events encapsulated by React. They are synthetic events and are managed by React.

React has a performance optimization mechanism for synthetic events and lifecycle functions. It will merge multiple setState . If attributes with the same name appear, the latter ones will overwrite the former ones .

If you bypass React's performance optimization mechanism and use setState in native events or setTimeout , it will no longer be managed by React. If you write setState several times, setState will be called several times.

This is the end of this article about how many times multiple setStates in React will be called. For more information about how many times multiple setStates in React will be called, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution to React pure function component setState not refreshing the page update
  • Code analysis of synchronous and asynchronous setState issues in React
  • Detailed explanation of React setState data update mechanism
  • Detailed explanation of react setState
  • The use of setState in React and the use of synchronous and asynchronous
  • Detailed explanation of setState callback function in React
  • A brief discussion of three points to note when using React.setState
  • In-depth study of setState source code in React

<<:  select the best presets to create full compatibility with all browsersselect

>>:  Theory: The two years of user experience

Recommend

3 methods to restore table structure from frm file in mysql [recommended]

When mysql is running normally, it is not difficu...

Tutorial on building nextcloud personal network disk with Docker

Table of contents 1. Introduction 2. Deployment E...

CSS Skills Collection - Classics among Classics

Remove the dotted box on the link Copy code The co...

Practical explanation of editing files, saving and exiting in linux

How to save and exit after editing a file in Linu...

Axios project with 77.9K GitHub repository: What are the things worth learning?

Table of contents Preface 1. Introduction to Axio...

Detailed explanation of Linux netstat command

Table of contents Linux netstat command 1. Detail...

Using JS to implement binary tree traversal algorithm example code

Table of contents Preface 1. Binary Tree 1.1. Tra...

MySQL Database Basics: A Summary of Basic Commands

Table of contents 1. Use help information 2. Crea...

The viewport in the meta tag controls the device screen css

Copy code The code is as follows: <meta name=&...

Vue+echart realizes double column chart

This article shares the specific code of vue+echa...

Detailed explanation of CSS3 flex box automatic filling writing

This article mainly introduces the detailed expla...

Small paging design

Let our users choose whether to move forward or ba...

MySQL turns off password strength verification

About password strength verification: [root@mysql...

UTF-8 and GB2312 web encoding

Recently, many students have asked me about web p...