React use constructor or just state

Hi,

Not sure if this is a preference thing or not, but I see that some people use a constructor when setting state, whereas other people don’t. Examples below.
Q: Any cons of just setting state and bypassing the extra characters typing up constructor?

class App extends Component {
 constructor(){
      super()
      this.state = {}
}
  render() {
    return (
      <div className="App">
        <h1>Test</h1>
      </div>
    );
  }
}

export default App;
class App extends Component {

 state = {}

  render() {
    return (
      <div className="App">
        <h1>Test</h1>
      </div>
    );
  }
}

export default App;

Second one is only a proposal to be added to JS. It probably will, hopefully this year, but it isn’t officially supported in any browser at the minute

Also, it is exactly equivalent to the first one. The tool Babel provides plugins to convert from the second form to the first automatically (so for example Create React App lets you use the second form out-of-the-box)

1 Like