Paweł Adamski Paweł Adamski - 1 year ago 235
React JSX Question

ReactJS - AJAX call in componentWillMount

React documentation suggest to fetch initial data in

function. For my it is not intuitive because we could do it sooner in
(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

  • Are there any benefits of using AJAX in

Answer Source

say you do AJAX on 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() {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download