React: asynchronous update of usestate

Time:2021-3-7

introduce

function App() {
  const [n, setN] = useState(0)
  const onClick = ()=>{
    setN(n+1)
    Set n (n + 1) // at this time, we find that n can only + 1, not + 2
    // setN(i=>i+1)
    // setN(i=>i+1)
  }
  return (
    <div className="App">
      <h1>n: {n}</h1>
      <button onClick={onClick}>+2</button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

The react code is shown in the figure above

  • Intuitively, when we click button, we should execute setn twice, and N becomes 2.
  • In fact: n becomes 1

Why is n 1 instead of 2?

First of all, we need to understand the principle of usestate. Please refer to my blog to explain the simple implementation of usestatehttps://segmentfault.com/a/11…

  • We know:

    1. Usestate returns a new state (equivalent copy of a simple type) each time it is executed
    2. Set state will trigger UI update (rerender, execute function component)
    3. Since UI update is an asynchronous task, setstate is also an asynchronous process

When we do it twicesetN(n+1)At that time, there were actually twoclosure, all save the reference to the state (n = 0) of N at this time.
After setn:

  1. First, two new n are generated, which are equal to N + 1 (i.e. 1), but they are independent of each other.
  2. Only the latest render is valid. This render refers to the N generated in the last setn function.

resolvent

//Use function to receive old value and update it
setState( x => x+1 )
  • Received functionx=>x+1Instead of maintaining a reference to N, it expresses aPlus 1operation
  • Function code is recommendedsetState