Nov 26, 2019 in React JS


In which lifecycle event do you make AJAX requests and why?

1 Answer

Nov 26, 2019

AJAX solicitations ought to go in the componentDidMount lifecycle event. 
There are a couple of reasons behind this, 

Fiber, the following usage of React's reconciliation algorithm, will be able to begin and quit rendering as required for execution benefits. One of the exchange offs of this is componentWillMount, the other lifecycle event where it may bode well to influence an AJAX to ask for, will be "non-deterministic". This means React may begin calling componentWillMount at different circumstances at whenever point it senses that it needs to. This would clearly be a bad formula for AJAX requests. 

You can't ensure the AJAX request won't resolve before the component mounts. In the event that it did, that would imply that you'd be attempting to setState on an unmounted component, which won't work, as well as React will holler at you for. Doing AJAX in componentDidMount will ensure that there's a component to update.

Click here to read more about React JS
Click here to read more about Insurance

Related questions

Feb 6 in JavaScript
May 29 in React JS
Sep 17, 2019 in React JS