Accepted answer

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.


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.


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.

Related Query

More Query from same tag