React setState: Synchronous or asynchronous? I believe most react technology stack applicants have been asked this question before. This article summarizes my understanding of this question and hopes to solve the confusion for students.

The author used to summarize the conclusions and rules by the running results of the code. Everything in the world has its rules. This paper will also summarize the answer to this question with some demos. This is also the most convincing, nonsense not to say, sauerkraut (wrong wrong… Is the code)

// demo1 
class App extends React.Component {
        state = {
          num: 0
        };
        componentDidMount() {
          	this.setState({
           	num: this.state.num + 1
           });
        	this.setState({
           	num: this.state.num + 2
          });
          console.log(this.state.num);
        }
 	render() {
          const { num } = this.state;
          return <div>{ num }</div>;
        }
      }
      ReactDOM.render(<App />, document.getElementById('root')); // The console prints 0, and the interface displays 2Copy the code

By displaying the results, we can draw the first conclusion: in the function scenario of life cycle, setState is asynchronous, multiple updates of the same state attribute will be merged into one, and the last update will be effective and reserved

// demo2
class App extends React.Component {
        state = {
          num: 0
        };
      handleClick = (a)= > {
          this.setState({
            num: this.state.num + 1
          });
          this.setState({
            num: this.state.num + 2
          });
          console.log(this.state.num); // Click the num console to print 0, and the interface displays 2
      };
 	render() {
         const { num } = this.state;
         return <div onClick={this.handleClick}>{ num }</div>;
        }
      }
      ReactDOM.render(<App />, document.getElementById('root'));
Copy the code

We registered a click event for div, after the interface rendering, num is 0, click num to display 2, the console prints 0, because the display result is the same, I did not have a picture, you can test yourself. According to the result, we can draw the second conclusion: in the scenario of React synthesis event, setState is asynchronous. The author will explain the concept of React synthesis event at the end of the article, and you can read the React source code. (Here the onClick event is not a JS native event, but a React synthesized event)

// demo3
class App extends React.Component {
        state = {
          num: 0
        };
        componentDidMount() {
       	  setTimeout((a)= > {
            this.setState({
              num: this.state.num + 1
            });
            this.setState({
              num: this.state.num + 2
            });
            console.log(this.state.num); // Console prints 3
          }, 1000);
        }
 	render() {
          const { num } = this.state;
          return <div>{ num }</div>;
        }
      }
      ReactDOM.render(<App />, document.getElementById('root'));
Copy the code

Conclusion three

React synthesizes events: Instead of binding the Click event directly to the DOM, React bubbles the event into a document, which then encapsulates the event into a formal function handler.

If too many event handlers are bound to the DOM, the overall page response and memory footprint can suffer. React implements an intermediate layer, SyntheticEvent, to avoid this kind of DOM event abuse and to mask the event system differences between the underlying browsers.

React does not bind the Click event to the DOM when the user adds a function to onClick. Instead, it listens for all supported events at document, and when the event happens and bubbles up to document, React encapsulates the event content to the middle layer SyntheticEvent, so when the event fires, The unified dispatch function dispatchEvent is used to specify function execution.

Summary: 1. In the case of life cycle functions, React synthesizes events asynchronously: multiple updates of the same state attribute (different state attributes do not affect it) are merged into one, and the last update is retained. 2. Synchronization in timer and native DOM event scenarios: updates are made sequentially