Is there a reason people prefer to use the React component constructor instead of componentWillMount?

I find that using the componentWillMount lifecycle method to set the initial state ...

 componentWillMount() { this.state = { comments: [] }; } 

... a little easier than using a constructor. Namely, because when using the constructor, you must call super() .

 constructor() { super(); this.state = { comments: [] }; } 

Not only that, but if your component is passed props and / or state , you also need to manually pass them.

 constructor(props, state) { super(props, state); ... } 

I had no problems using componentWillMount , but I almost never saw anyone use it to set the state (unless they avoid es6 and have classes). I get that we have access to the constructor in the es6 class, but why use it when you need to make a manual transition to the parent constructor, and there is a ready-made and expecting an excellent life cycle, so you do not need to do this

Just curious if there was a real practical reason or if it is basically just a preference.

+7
javascript reactjs
source share
2 answers

The constructor is the only "correct" place for initialization (direct assignment) of state . those. this.state = {...}

The rest of the functions that you define inside the component ( componentWillMount , etc.) are called "lifecycle callbacks" called by the React engine. It is expected that state should be unchanged throughout the component life cycle and should never be directly assigned. Instead, you will need this.setState({...}) to make any changes to state outside the constructor.

While your current practice may still not have caused any problems, it does not guarantee continued work in the same way. If for some reason React reads state between lifecycle callbacks and you change it in your componentWillMount callback, this could lead to unforeseen consequences.

My advice would be to only ever directly initialize state in your constructor and use setState everywhere.

If verbosity is troubling, and you have no other purpose for the constructor than initializing your state , and you don't need to props initialize state , just declare and initialize the state property:

 class MyComponent extends React.Component { state = {} } 
+7
source share

Good according to DOCS :

Generally, we recommend using the constructor () instead.

He also noted that:

This is the only lifecycle hook that is called when rendering a server.

So, I think this may be part of the reason.

+2
source share

All Articles