Why is this react component rendering twice? Why is this react component rendering twice? reactjs reactjs

Why is this react component rendering twice?


You have a async request in componentWillMount, so before the request is completed, your component is rendered, however once the async request is successful you have a setState function call which triggers a re-render and hence your component is getting rendered twice

This is an expected behaviour.

You can check this question for more details

Use componentWillMount or componentDidMount lifecycle functions for async request in React

According to the docs

componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering.

This means that if you write

componentWillMount() {   this.setState({count: 1});}

the state will be reflected in the initial render itself and no-render is triggered. However if you have a async method then calling setState inside it might trigger an extra render if the async request gets completed after the render is already called.

To emphasize more on the fact, you must not use componentWillMount any more, since React is oncourse to remove this method from future major realease. Instead use componentDidMount.