Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"

like image 558
seldon Avatar asked Oct 28 '14 18:10

seldon


2 Answers

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>
}
like image 121
Brigand Avatar answered Nov 23 '22 23:11

Brigand


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.

like image 45
zackify Avatar answered Nov 24 '22 00:11

zackify