javascript - Since setState is asynchronous, is it executed via callback queue? - Stack Overflow

I am new to React and was learnig how setState works behind the scenes. Thus I would like to ask some q

I am new to React and was learnig how setState works behind the scenes. Thus I would like to ask some questions on it. Firstly, is setState always asynchronous? if not in what general situations it is synchronous. Secondly, how asynchrony happens in setState is it executed via web api and then callback queue? Guys if something is not clear please let me know. I just really need your help.

I am new to React and was learnig how setState works behind the scenes. Thus I would like to ask some questions on it. Firstly, is setState always asynchronous? if not in what general situations it is synchronous. Secondly, how asynchrony happens in setState is it executed via web api and then callback queue? Guys if something is not clear please let me know. I just really need your help.

Share Improve this question edited Aug 30, 2019 at 6:38 Dickens asked Aug 30, 2019 at 6:26 DickensDickens 9154 gold badges12 silver badges27 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Yes. it's always asynchronous and never synchronous. mon mistakes by developers is something like this

 handleEvent(newValue) {
   this.setState({ value: newValue }, () => {
      // you can get the updated state here
      console.log(this.state.value)
   })
   this.doSomething(newValue)
 }

 doSomething(newValue) {
   // this.state.value is still the old value
   if (this.state.value === newValue) {
      // blabla
   }
 }

And you can't determine how much time it will take for the state to update.

React setState is not always asynchronous, it depends upon how state change was triggered.

1) Synchronous - If the action is outside of Reactjs world or if the state change was triggered by timer or user induced event handler, then reactjs can't batch updates and has to mutate the state immediately.

2) Asynchronous If the state change is triggered by onClick, then Reactjs can batch updates to the state for performance gains.

Working codesandbox link

and

Reference post

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  state = {
    counter: 0
  };
  ponentDidMount() {
    // const intervalId = setInterval(this.updateState, 5000);
    // this.setState({intervalId: intervalId});
    this.counter.addEventListener("mousedown", this.updateState);
  }
  ponentWillUnmount() {
    this.counter.removeEventListener("mousedown", this.updateState);
    // clearInterval(this.state.intervalId);
  }
  updateState = event => {
    console.log("= = = = = = = = = = = =");
    console.log("EVENT:", event ? event.type : "timer");
    console.log("Pre-setState:", this.state.counter);
    this.setState({
      counter: this.state.counter + 1
    });
    console.log("Post-setState:", this.state.counter);
  };
  render() {
    return (
      <div className="App">
        <span onClick={this.updateState} ref={elem => (this.counter = elem)}>
          Counter at {this.state.counter}
        </span>
      </div>
    );
  }
}

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

console logs

    = = = = = = = = = = = =
    EVENT: mousedown 
    Pre-setState: 
    0
    Post-setState: 
    1
    = = = = = = = = = = = = 
    EVENT: click 
    Pre-setState: 
    1
    Post-setState: 
    1

As you can see in console logs, mousedown event state change is immediately reflected but onClick change is asynchronous or better said batched.

So its better we assume the state change will be asynchronous and use callback handler to avoid bugs. And off-course anything inside callback will go through event loop in javascript.

Hope that helps!!!

Yes. it's asynchronous. And in Javascript asynchronous actions are handled using event loop

https://www.youtube./watch?v=8aGhZQkoFbQ

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745483551a4629666.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信