What is the difference between componentWillMount and componentDidMount in ReactJS?

componentWillMount is essentially the constructor. You can set instance properties that don't affect render, pull data from a store synchronously and setState with it, and other simple side effect free code you need to run when setting up your component.

It's rarely needed, and not at all with ES6 classes.


the constructor method is not the same as componentWillMount.

According to the author of Redux, it is risky to dispatch actions from the constructor because it may result in mutating the state while rendering.

However, dispatching from componentWillMount is just fine.

from github issue:

This happens when dispatch() inside one component's constructor causes a setState() inside another component. React keeps track of the “current owner” for such warnings—and it thinks we're calling setState() inside the constructor when technically constructor causes a setState() inside some other part of the application. I don't think we should handle this—it's just React trying its best do its job. The solution is, as you correctly noted, to dispatch() inside componentWillMount() instead.


To add to what FakeRainBrigand said, componentWillMount gets called when rendering React on the server and on the client, but componentDidMount is only called on the client.

Tags:

Reactjs