Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the update mechanism of setState in React

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the update mechanism of setState in React". In daily operation, I believe that many people have doubts about the update mechanism of setState in React. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is the update mechanism of setState in React?" Next, please follow the editor to study!

As an important part of react, setState queues changes to the component state and informs React that it needs to re-render the component and its subcomponents using the updated state.

State is an important concept in React. We know that React manages components through state management. So, how does React control the state of components, and how does it use state to manage components? [related recommendation: Redis video tutorial]

As we all know, React accesses state through this.state and updates state through the this.setState () method. When this.setState () is called, React re-calls the render method to re-render the UI.

SetState is already an API that we are very familiar with, but do you really know it? Next we will decrypt the update mechanism of setState.

SetState async update

When you start to write React, you usually write code like this.state.value = 1, which is completely wrong.

Note: never modify this.state directly, which is not only inefficient, but also likely to be replaced by later operations.

SetState implements state updates through a queuing mechanism. When the setState is executed, the state that needs to be updated will be merged and put into the status alignment, instead of updating the this.state immediately, and the queue mechanism can update the state in batches efficiently. If the value of this.state is not modified directly through setState, then the state will not be placed in the status queue. The next time setState is called and the status queue is merged, the previously directly modified state will be ignored, resulting in an unpredictable error.

Therefore, the setState method should be used to update state, and React uses the state queue mechanism to achieve asynchronous updates of setState to avoid frequent repeated updates of state. The related code is as follows:

/ / merge the new state into the status update queue var nextState = this._processPendingState (nextProps, nextContext); / / determine whether the component needs to be updated according to the status of the update queue and shouldComponentUpdate var shouldUpdate = this._pendingForceUpdte | |! inst.shouldCompoonentUpdate | | inst.shouldComponentUpdate (nextProps, nextState, nextContext0;setState cyclic call risk

When setState is called, the enqueueSetState method is actually executed, merging the partialState and _ pendingStateQueue update queues, and finally operating enqueueSetState to perform the state update.

The performUpdateIfNecessary method gets _ pendingElement, _ pendingStateQueue, _ pendingForceUpdate, and calls the receiveComponent and updateComponent methods to update the component.

If setState is called in the shouldComponetUpdate or componentWillUpdate method, this._pendingStateQueue! = null, the performUpateIfNecessary method will call the updateComponent method to update the component, but the updateComponent method will call the shouldComponentUpdate and componentWillUpdate methods, resulting in a circular call, causing the browser to crash after running out of memory.

SetState call stack

Since setState ultimately performs state updates through enqueueUpate, how exactly does enqueueUpdate update state?

First of all, let's take a look at the following question. Can you answer it correctly?

Import React {Component} from 'react'class Example extends Component {constructor () {super () this.state = {val: 0}} componentDidMount () {this.setState ({val: this.state.val + 1}) console.log (this.state.val) this.setState ({val: this.state.val + 1}) console.log (this.state.val) setTimeout (() = > {this.setState ({val: this.state.val + 1}) console.log (this.state.val) this.setState ({val: this.state.val + 1}) console.log (this.state.val)} 0)} render () {return null}}

In the above code, the val printed by console.log four times is: 0, 0, 2, 3, respectively.

If the result is not exactly the same as the answer in your mind, do you want to know what enqueueUpdate did? The following figure is a simplified setState call stack, pay attention to the state judgment of the core.

SetState simplifies the call stack

Decrypt setState

How on earth does it lead to the different performances of setState?

First of all, we need to understand how transactions relate to the different performance of setState. First of all, we simply categorize the four setState, the first two belong to one category, because they execute in the same call stack, and the two setState in setTimeout belong to the other, because they also execute in the same call stack. Let's analyze the call stack for these two types of setState.

The call stack of two calls to setState directly in componentDidMount is more complex, while the call stack of two calls to setState in setTimeout is much simpler. Let's focus on the call stack of the first type of setState. We found that the batchedUpdates method was already in the transaction executed by batchedUpdates long before the setState call.

So who called the batchedUpdates method? Let's go back a little further and it turns out to be the _ renderNewRootComponent method in ReactMount.js. That is, the whole process of rendering React components into DOM is in one big transaction.

The next explanation makes sense, because when setState is called in componentDidMount, the isBatchingUpdates of batchingStrategy has been set to true, so the results of the two setState are not immediately effective, but are put into dirtyComponents. This also explains why both printing this.state.val is 0, because the new state has not yet been applied to the component.

The call stack of setState in componentDidMount

The call stack of setState in setTimeout

Looking back at the two setState in setTimeout, because there is no preceding batchedUpdate call, the isBatchingUpates flag bit of batchingStrategy is false, which causes the new state to take effect immediately and does not go to the dirtyComponents branch. That is, the first time setState is executed in setTimeout, the this.state.val is 1, but when setState finishes printing, the this.state.val becomes 2. The second setState is the same.

When introducing transactions earlier, we also mentioned a number of applications in React source code, such as initialize, perform, close, closeAll, motifyAll and other methods appear in the call stack, indicating that we are currently in a transaction.

Since transactions are so useful, can we use them when writing application code? Unfortunately, the answer is no. Although React does not recommend that we use transactions directly, the batchedUpdates method is provided for developers prior to React 15.00.It can solve the situation where two setState in setTimeout in the initial example results in two render:

Import ReactDOM, {unstable_batchedUpates} from 'teact-dom'unstable_batchedUpates (() = > {this.setState (val: this.state.val + 1) this.setState (val: this.state.val + 1)})

In React 15.0 and later, the batchUpdates API has been completely removed, so developers are no longer recommended to use it.

At this point, the study on "what is the update mechanism of setState in React" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report