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

Detailed description of ffmpeg Chinese parameters

FFMPEG 3.4.1 version parameter details Usage: ffm...

Use of Linux file command

1. Command Introduction The file command is used ...

PHP scheduled backup MySQL and mysqldump syntax parameters detailed

First, let's introduce several common operati...

Summary of Commonly Used MySQL Commands in Linux Operating System

Here are some common MySQL commands for you: -- S...

Use auto.js to realize the automatic daily check-in function

Use auto.js to automate daily check-in Due to the...

Add crontab scheduled tasks to debian docker container

Now most of the Docker images are based on Debian...

TinyEditor is a simple and easy-to-use HTML WYSIWYG editor

A few days ago, I introduced to you a domestic xh...

Building an image server with FastDFS under Linux

Table of contents Server Planning 1. Install syst...

Sample code for implementing music player with native JS

This article mainly introduces the sample code of...

Example of using MySQL to count the number of different values ​​in a column

Preface The requirement implemented in this artic...

MySQL data archiving tool mysql_archiver detailed explanation

Table of contents I. Overview 2. pt-archiver main...

Detailed explanation of MySQL 30 military rules

1. Basic Specifications (1) InnoDB storage engine...

About the correct way to convert time in js when importing excel

Table of contents 1. Basics 2. Problem Descriptio...