SoFunction
Updated on 2025-04-07

Detailed explanation of the setState execution mechanism in React

1. What is setState

It is a method used in React components to update state. It is a method in a class component that updates the state of the component and re-renders the component.
The setState method accepts an object or a function as an argument. When an object is passed, it merges the object into the current state object and triggers the component's re-rendering. When passing a function, the function will receive the previous state as a parameter and return a new state object. The setState method will then merge the returned state object into the current state.

Simple example

class MyComponent extends  {
  constructor(props) {
    super(props);
     = {
      count: 0
    };
  }

  incrementCount() {
    ({ count:  + 1 });
  }

  render() {
    return (
      <div>
        <p>Count: {}</p>
        <button onClick={() => ()}>Increment</button>
      </div>
    );
  }
}

There is one herecountproperty. When the user clicks a button, callincrementCountMethod, this method usessetStaterenewcountThe value of the property triggers the re-render of the component, and displays the updated count value on the page.

2. Update type

When using setState to update data,setStateThe update types are divided into:

  • Asynchronous update
  • Synchronous updates

Asynchronous update

When calledsetStateWhen the method,ReactUpdate requests are placed in the queue and batched when appropriate, and then the status of the component is updated in batches. This means that it is invokedsetStateAfter that, the status value of the component is not changed immediately, but is updated at a later point in time.

The advantage of asynchronous updates is that they can improve performance and avoid unnecessary duplicate rendering. When called multiple timessetStatehour,ReactThese updates are merged into one update, triggering only one re-render.

changeAge() {
  ({
    age: 22
  })
  (); // It will not be 22, it is a previous value}

This does not see the latest state results

changeText() {
  ({
    age: 22
  }, () => {
    (); // 22
  });
}

Synchronous updates

In some cases, it is necessary to get the latest status value immediately, rather than waiting for an asynchronous update. To achieve synchronous updates, setState in the form of a callback function can be used.

SetState in the form of a callback function receives a function as a parameter, which can accept the previous state and attribute as a parameter and return a new state object. React will execute the function immediately and update it using the returned state object.

componentDidMount() {
  const btn = ("btn");
  ('click', () =&gt; {
    ({
      mes: "Hello, white whale"
    });
    (); // Hello, white whale  })
}

summary

  • In componentsLifecycle or React synthesis eventmiddle,setStateyesasynchronousof
  • existsetTimeout or native dom eventmiddle,setStateyessynchronousof

State assignment

Three situations

1. Normally assigned values

Types used are: numbers, strings, booleans, null, undefined

({
  count: 1,
  title: 'setState',
  success: true
})

2. Assignment of array type

Methods to increase a value

// Method 1: Assign state to another variable first, and then use concat to create a new arrayvar hobaies= ; 
({
  hobaies: (['basketball']);
})
// Method 2: Use preState and concat to create a new array(preState =&gt; ({
  hobaies: (['basketball']);
}))
// Method 3: ES6 array extension(preState =&gt; ({
  hobaies: [..., 'basketball'];
}))

3. Assignment of object types

// Method 1: Uselet ages= ;
({
  owner: ({}, ages, {age: 22});
})
// Method 2: Use preState and create a new object(preState =&gt; ({
  owner: ({}, , {age: 22});
}))

I’ll learn this today and will update it if I have in-depth understanding in the future.

The above is a detailed explanation of the setState execution mechanism in React. For more information about the React setState execution mechanism, please follow my other related articles!