Paweł Adamski Paweł Adamski - 3 months ago 82
React JSX Question

ReactJS - AJAX call in componentWillMount

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:


  • Are there any problems with using AJAX in
    componentWillMount
    ?

  • Are there any benefits of using AJAX in
    componentDidMount
    ?


Answer

say you do AJAX on componentWillMount

componentWillMount(){
   this.serverRequest = $.get(...);
}

Now you have a pending AJAX request. To not leak memory its a usually 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