SoFunction
Updated on 2025-04-07

Detailed explanation of the use of state of React's three major attributes

Data is needed in many places in React, which is called state in React. We need a method to specifically manage states, so state-related things were born. The state should be required to have two basic functions: one is to store a certain value so that it can be used by react, and the other is to be listened to and re-rendered when it changes. Here we introduce the writing method of state in class and function components:

Class Components

class ClassComponent extends {
    constructor(props){
        super(props)
    } //Writable or not    render(){
        return (
            //You can write jsx syntax here        )
    }
}

We generally use setState to change the state. In it, you can directly pass an object to be changed, or you can pass a callback function. Note that if the object is passed in at this time, React only makes a shallow copy, not a deep copy, so if there are other objects in the object, React cannot know how to render. This method essentially passes in a new value and overwrites the original value. If this value is the same as the original value, then React will not render.

Why is React so troublesome? It cannot directly modify the value? Because in React, there is a concept called variability. React knows where the state changes in setState, so it renders. If the state is changed directly, React cannot sense it, so it cannot render. Simply put, it does not have two-way data binding like vue.

The constructor in the class component can be written or not. There are two main functions of writing this constructor:

  • In order to initialize the value of the internal state to the assignment object
constructor(props){
    super(props)
     = {n:12}
}

render(){
    return (
        <div>
                <h1>THE TIME IS {}</h1>
        </div>
    )
}

Note that you cannot write setState here. The above method React can also be set outside, that is,

state = {n:12}

render(){
    return (
        <div>
            <h1>THE TIME IS {}</h1>
        </div>
    )
}
  • Binding instances for event handlers
constructor(props){
    super(props)
     = function(){fn()}.bind(this)
}

render(){
    return (
        <button onClick={}>+1</button>
    )
}

However, this method has new methods replaced in React, the code is as follows:

addNum = ()=>{
    fn()
}

render(){
    return (
        <button onClick={}>+1</button>
    )
}

Therefore, there is no need to write the above constructor to inherit the parent class.

Function Components

import {useState} from "react"
function FunctionComponent(){
    const [data,setData] = useState("The initial value you want to pass in")
    return (
        &lt;div&gt;SHOW DATA {state}&lt;/div&gt;
    )
}

The function of setData here is similar to setState, but it can only be used to change the state of data. When it needs to be changed, a callback function is passed. The parameter of the function is the previous value, returning a value to be changed. This method essentially needs to pass in a new object to change the value of the object before React. This can also be written directly directly to write the changed value, which will correspond to the current object and change its value by default.
The above method is much simpler than the original setState, but the trouble is that if there are multiple data, you need to useState multiple times and cannot pass multiple values ​​in one go. However, in most cases, data management issues are left to Redux to manage, so React itself does not need to worry about it.

The pit of setState

When changing the state of React components, the problem that is often encountered is the merge of setState values. Look at the following questions:

 = function () {
            ({num:+1})
            ({num:+1})
            ({num:+1})
        }.bind(this)

At this time, when the addNum function is triggered, only 1 is added to num. There is no addition of 3 as we thought. In this regard, React itself explains

Calling setState is actually asynchronous - don't expect that after calling setState, it will be mapped to a new value immediately

The explanation for this is:

  1. No matter how many times setState is called, the update will not be performed immediately. Instead, the state to be updated is stored in '_pendingStateQuene' and the component to be updated is stored in 'dirtyComponent';
  2. When the root component didMount, the batch processing mechanism is updated to false. At this time, the state and components in '_pendingStateQuene' and 'dirtyComponent' are taken out for merge and update;

Simply put, when React executes, in order to improve performance, the setState to be updated will be stored in an array. When the synchronization code of React itself is executed, before updating, the setState in the array will be taken out and then rendered. In the above code, because we added the synchronization code ({num:+1}) to setState, we will generate a merge when the batch is fetched, and many setStates will be merged into one sentence, thus only changing 1. Because of this mechanism, setState is like asynchronous code, but in fact it is executed synchronously. At this time, if we change the previous synchronous code to asynchronous, we will get the result we want

 = function () {
            setTimeout(()=>{ ({num:+1}) },0)
            setTimeout(()=>{ ({num:+1}) },0)
            setTimeout(()=>{ ({num:+1}) },0)
        }.bind(this)

At this time, the value is directly increased by 3, because the asynchronous code will be temporarily stored when the code is executed. Execute again when all synchronous code is executed. At this time, the batch processing mechanism has ended, so all three functions are executed, so 3 is added. This is what you can think of so far. If there is new one in the future, it will be added.

The above is the detailed explanation of the use of the three major React attribute states. For more information about the three major React attribute states, please follow my other related articles!