Search code examples
javascriptreactjssetstate

Why do the async function works after this.setState?


Assuming I have the following code;

ComponentDidMount(){
  const res = fetch(smth) 

  this.setState({data: res}) // first setState

  const res2 = fetch(another)

  this.setState({data2: res2}) // second setState
}

The issue is that both setState will work. I was thinking that first setState calls render() and the component reloads and the code after the first setState will not work

Why?


Solution

  • According to the docs:

    componentDidMount() is invoked immediately after a component is mounted (inserted into the tree)....... You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state.

    Which means that all the codes in "componentDidMount()" get called before the user sees the result in render().