seldon
seldon

Reputation: 1027

Why async requests should be made in componentDidMount instead of getInitialState in ReactJS?

This page of React's docs shows that async requested data should be consumed in the componentDidMount event, while getInitialState initialize the state object to a default empty state.

Is there a reason for that? Maybe getInitialState is not expected to do this or has a different purpose? Is it due to some internal logic of the library?

Note to moderators and answerers: this isn't an opinion-based question: if a reason exists, that would be the answer, however, a good, correct answer to my question could be as well "No, there isn't any particular reason, do whatever you feel better"

Upvotes: 20

Views: 4814

Answers (2)

Brigand
Brigand

Reputation: 86250

getInitialState should be a pure function of props (though they often aren't used). In other words, with the same props getInitialState should return the same data.

componentDidMount is allowed to have dynamic behavior, and cause side effects such as dom manipulation and ajax requests (that's the main intention of it).

A common way to handle this is with an early return of either an empty div, loading message, <div>Loading</div>), or loading indicator (e.g. spinkit).

On first render the spinner will be shown, and then eventually state is updated with data and the main part of render can be run.

render: function(){
   // while loading
   if (!this.state.data){
     return <div className="spinner"></div>
   }

   // loaded, you can use this.state.data here
   return <div>...</div>
}

Upvotes: 11

zackify
zackify

Reputation: 5434

You wouldn't want to do this because your component will be waiting on the async request and it won't be able to mount until it's finished. If you have html with a couple state variables, let react render first instead of making it wait. I know this is an opinion but it's also a separation of concerns thing as well.

Upvotes: 2

Related Questions