Why do the React docs recommend doing AJAX in componentDidMount, not componentWillMount?
I understand why componentDidMount
is appropriate for anything that requires DOM access, but an AJAX request doesn’t necessarily or usually need this.
What gives?
Solution 1:
componentDidMount
is for side effects. Adding event listeners, AJAX, mutating the DOM, etc.
componentWillMount
is rarely useful; especially if you care about server side rendering (adding event listeners causes errors and leaks, and lots of other stuff that can go wrong).
There is talk about removing componentWillMount
from class components since it serves the same purpose as the constructor. It will remain on createClass
components.
Solution 2:
I had the same issue at the beginning, too. I decided to give a try making requests in componentWillMount
but it end up in various small issues.
I was triggering rendering when ajax call finishes with new data. At some point rendering of component took more time than getting response from server and at this point ajax callback was triggering render on unmounted component. This is kind of edge case but there is probably more, so it's safer to stick to componentDidMount
.
Solution 3:
According to documentation setting the state in componentWillMount
will no trigger a re-rendering.
If the AJAX call is not blocking and you return a Promise
that update the component's state on success, there are chances that the response arrives once the component has been rendered.
As componentWillMount
doesn't trigger a re-render you won't have the behaviour you expected which is the component being rendered with the requested data.
If you use any of the flux libraries and the data requested end up in the store the component is connected to (or inherit from a connected component) this won't be an issue as the reception of that data will, most likely, change props eventually.