52

In react components is it preferred to set the initial state in the constructor() or componentWillMount()?

export default class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this.setState({key: value});
  }
}

or

export default class MyComponent extends React.Component{
  componentWillMount(props){
    this.setState({key: value});
  }
}
freedrull
  • 2,194
  • 4
  • 21
  • 33
  • http://stackoverflow.com/questions/38137740/which-kinds-of-initialization-is-more-appropriate-in-constructor-vs-componentwil – Asaf David Aug 10 '16 at 07:22

1 Answers1

79

In the constructor is preferable when using ES6 classes, but don't use the setState API, rather do like so:

export default class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this.state = { key: value };
  }
}

Also, if you have class properties available to you (babel stage 1) then you can do the following:

export default class MyComponent extends React.Component{
  state = { key: value };

  render() {
    ....
  }
}
ctrlplusb
  • 12,847
  • 6
  • 55
  • 57
  • Because I remember reading to never mutate this.state directly : https://facebook.github.io/react/docs/component-api.html#setstate – freedrull Jun 13 '16 at 05:38
  • 11
    Sorry, to be clear, don't use it when setting initial state. :) Everywhere else yes. – ctrlplusb Jun 13 '16 at 05:39
  • Why is it ok in this case? – freedrull Jun 16 '16 at 08:39
  • 2
    Also why is it better to use the constructor than componentWillMount? – freedrull Jun 16 '16 at 08:39
  • 4
    It's a direct recommendation from the React team to set the state in the constructor when using ES6 classes. [Read about that here](https://facebook.github.io/react/docs/reusable-components.html#es6-classes). I assume there is some level of internals that we are unaware of which require the initial state to be set before any lifecycle events get fired. – ctrlplusb Jun 16 '16 at 08:51
  • I'm reading a book and it sets initial state in componentWillMount which made me curious why not in constructor. Just saying that not all books can be trusted for best practice. – Marina Dunst Mar 21 '17 at 17:42
  • Why use `this.state` in your first code and only `state` in the second?I dint get that – Abhinav Feb 25 '18 at 09:33
  • +Abhinav first code refers to the class's property from a function in the same class, while the second code declares the class property, along with its initial value (so `this` is not needed). Essentially, the assignment does not happen in a function context (although the transpiled version does but that's an implementation detail). – joonas.fi May 26 '18 at 05:46