michele
michele

Reputation: 23

React: What is the core difference between setting a state in a constructor vs. just setting the state within the class?

What is the core difference here? I have used both in similar ways with success. But what is happening behind the scenes that makes them different and when should each approach be used?

class Store extends React.Component { 
  constructor(props){
    super(props)
    this.state =  {
      checked: false
    }
}

vs.

class Store extends React.Component { 
  state = { checked: false }
}

Upvotes: 1

Views: 87

Answers (1)

devserkan
devserkan

Reputation: 17608

There is no "should" for those two methods. Your second example is a new proposal: class-fields. This is it. So, if you don't need to use the constructor, you can skip it and define your state, also the class methods if you need them, like your second example.

You need Babel and a specific plugin to use this new proposal. Since you can use it successfully, this means you already have this plugin. Behind the scenes your second code is compiled into something like this:

class Store extends React.Component {
  constructor(...args) {
    var _temp;

    return (_temp = super(...args)), (this.state = { checked: false }), _temp;
  }
}

Upvotes: 2

Related Questions