Reputation: 3415
React documentation suggest to fetch initial data in componentDidMount
function. For my it is not intuitive because we could do it sooner in componentWillMount
(first function from React component life cycle). In general I think we should start AJAX calls us soon us possible so user doesn't have to wait for them. So why do we have to wait until component is rendered?
My questions are:
componentWillMount
?componentDidMount
?Upvotes: 0
Views: 1692
Reputation: 1159
say you do AJAX on componentWillMount
componentWillMount(){
this.serverRequest = $.get(...);
}
Now you have a pending AJAX request. Its a good practice to cancel this request when the component is unmounted
componentWillUnmount: function() {
this.serverRequest.abort();
}
but lets say for whatever reason the component did not mount. you still have your pending ajax request which can not be cancelled anywhere (since component is not mounted, componentWillUnmount
won't be reached) thus creating a memory leak.
If you had put the ajax request on componentDidMount
you had a guarantee that the componentWillUnmount
will fire since component is mounted allowing you to cleanup your request safely
Upvotes: 7
Reputation: 1576
Simply create the component when you have the data and pass it through props. Have the parent component (if you have one) to do the request.
Upvotes: 1