Is it better to define state in constructor or using property initializers?

abustamam picture abustamam · Jun 13, 2016 · Viewed 15.7k times · Source

According to this babel documentation, the correct way to use ES6+ with React is to initial components like this:

class Video extends React.Component {
  static defaultProps = {
    autoPlay: false,
    maxLoops: 10,
  }
  static propTypes = {
    autoPlay: React.PropTypes.bool.isRequired,
    maxLoops: React.PropTypes.number.isRequired,
    posterFrameSrc: React.PropTypes.string.isRequired,
    videoSrc: React.PropTypes.string.isRequired,
  }
  state = {
    loopsRemaining: this.props.maxLoops,
  }
}

But some official examples, like Dan Abramov's own React DnD module, uses ES6+ but still defines state within the constructor:

constructor(props) {
    super(props);
    this.moveCard = this.moveCard.bind(this);
    this.state = {
       // state stuff
    }
}

Now Dan Abramov, being a significant contributor to React, probably knows that he can define state outside the constructor, yet still opts to do it within the constructor.

So I'm just wondering which way is better and why?

Answer

ctrlplusb picture ctrlplusb · Jun 13, 2016

I believe it's a matter of personal preference. The transpiled output is the same in terms of semantics.