Is setState asynchronous or synchronous?
React? SetState is synchronous or asynchronous? React is asynchronous in its lifecycle function or scope and synchronous in its native environment. Even if you think you got it right, you didn't. Now let's analyze setState in different cases.Copy the code
Synchronous:
So in what case is synchronization? When not using ConcurrentCopy the code
Native environment
componentDidMount(){
document.body.addEventListener('click', this.changeNum, false);
setTimeout(()=>{
this.setState({num:1})
console.log('--1--',this.state.num)
},0)
}
changeNum = () => {
this.setState({
num:2
})
console.log('--2--',this.state.num)
}
Copy the code
It’s going to be –1– 1– 2– 2 and it’s going to be num changed, so it’s synchronized, and I’m not going to go into that
FlushSync function under
With the release of React 17, reactdom.flushsync is now allowed to be used in its lifecycle (but waring)Copy the code
click(){
console.log('--1--',this.state.num)
flushSync(()=>{
this.setState({
num:1
})
})
console.log('--2--',this.state.num)
}
Copy the code
As you know, Fiber has made rendering more user-friendly. React will render the high priority first, then free the JS thread to do other things, such as animation rendering, and then render the low priority after it is finished. FlushSync increases the priority of rendering.
Pseudo asynchrony in the React environment
click = () => { console.log('--1--',this.state.num) this.setState({ num:1 },()=>{ console.log('--3--',this.state.num) }) console.log('--2--',this.state.num) }Copy the code
The result is –1– 0 –2– 0 –3– 1 and while the result looks asynchronous, it’s actually pseudo-asynchronous. The setState here is simply passing the new state to the update ue list, which is the updateQueue, and waiting for the click event to end will trigger the internal callback function to actually update the state and rerender.
True asynchronous ConcurrentMode component wrap
When a Concurrent component is used, a truly asynchronous update mode is performed, and of course the latest state is not immediately available, it is executed using (postMessage). However, this mode is still experimental, which means the current stable version of React won’t work. Have to understand in detail to react website reactjs.bootcss.com/docs/concur… The above is my understanding of setState, if there is any mistake, thank you for pointing out