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?
3 Answers 3
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.
9 Comments
componentWillMount? I don’t really see the distinction.componentWillMount will be executed on a serverside render. Wheras if you were using componentDidMount then that would only be executed on clientside. As a result putting things in componentWillMount that perform external interactions or bind to events etc, is not a great idea. If you have no plans to render your components on serverside, it's still not a good idea just for potential code portability. This is all outside the main reason it's bad which is explained in @daniula 's answer.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.
7 Comments
componentWillMount, so you should still keep using componentDidMount for your ajax calls.setState in a component constructor and you have no way of determining when the AJAX call will complete. twitter.com/dan_abramov/status/576453138598723585 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.
1 Comment
componentWillMount does not trigger a re-render just because a new state is defined before the first render. But if setState is called in a AJAX callback, it will be most definitely called after the first render, and it will trigger a re-render.
componentWillMountit would fail given that the component...didn't mount.