What is the difference between componentWillMount and componentDidMount in ReactJS?
I looked at Facebook's documentation at (React.Component) and it mentions how componentWillMount
is invoked on the client/server whereas componentDidMount
is invoked only on the client. What does componentWillMount
do to the server?
Solution 1:
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.
Solution 2:
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.