0 votes
in ReactJS by

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

1 Answer

0 votes
by

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.

Related questions

0 votes
0 votes
asked Nov 17, 2020 in JQuery by rajeshsharma
0 votes
asked Aug 9, 2023 in AJAX by Robin
...