I find that using the lifecycle method componentWillMount
to setup initial state...
componentWillMount() {
this.state = {
comments: []
};
}
...is slightly simpler than using the constructor. Namely because when you use the constructor you have to call super()
.
constructor() {
super();
this.state = {
comments: []
};
}
Not only that but if your component is passed props
and/or state
then you have to manually pass those through as well.
constructor(props, state) {
super(props, state);
...
}
I haven't had any problems using componentWillMount
but I virtually never see anyone using it for setting up state (unless they are avoiding es6 and don't have classes). I get that we have access to the constructor in an es6 class, but why use it when you have to wire a manual passthrough to the parent constructor and there is a perfectly good lifecycle method ready and waiting so you don't have to do that?
Just curious if there was an actual practical reason or if it's mostly just preference.
Constructor is the only "correct" place to initialize (directly assign to) state
. i.e. this.state = {...}
The rest of the functions you define within the component (componentWillMount
, etc.) are so called "lifecycle callbacks" invoked by the React engine. It is expected that state
should be immutable throughout the lifetime of the component and must never be directly assigned to. Instead, you'd have to this.setState({...})
in order to effect any changes to the state
anywhere outside the constructor.
While your current practice may not so far have caused any issues, it's not guaranteed to continue working in the same way. If for some reason React reads state
between lifecycle callbacks, and you have mutated it in your componentWillMount
callback, this may create unintended consequences.
My advice would be to only ever directly initialize state
in your constructor, and use setState
everywhere else.
If verbosity is a concern and you have no other purpose for the constructor than initializing your state
, and you don't need the props
to initialize your state
, simply declare and initialize your state property:
class MyComponent extends React.Component {
state = {}
}
Well according to the DOCS:
Generally, we recommend using the constructor() instead.
It also mentioned that:
This is the only lifecycle hook called on server rendering.
So i guess this could be part of the reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With