Skip to content

Recommend using componentWillMount instead of using a constructor #10972

@jonricaurte

Description

@jonricaurte

Do you want to request a feature or report a bug?
feature

What is the current behavior?
In the docs it is recommended to use the constructor over componentWillMount.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem via https://jsfiddle.net or similar (template: https://jsfiddle.net/ebsrpraL/).

What is the expected behavior?
Recommend using componentWillMount over a constructor. In ES6 classes React does not have to provide a lifecycle hook before mounting since constructors are already defined, however, constructors are generally confusing considering they have their own ways of defining things in React. Take the following example from the tutorial:

constructor(props) {
  super(props);
  this.state = {
    color: props.initialColor
  };
}

If this were written in componentWillMount, it would look like the following:

componentWillMount() {
  const { initialColor } = this.props;
  this.setState({
    color: initialColor
  });
}

There is no weird having to pass to super(props) which only happens in constructors and nowhere else in React. Also setting state is different only in the constructor and nowhere else in React. Using componentWillMount, you extract props like you normally would in any other method in a React class. Also setting state is exactly the same as every other method in a React class. I feel like having the consistency of componentWillMount is better even though ES6 classes do provide a constructor. componentWillMount also supports server rendering. Are there any benefits performance wise using a constructor over componentWillMount? Thanks!

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
React 16

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions