0

I have seen some reactjs courses where the component state is directly initialized without using a constructor as shown below.

class App extends React.Component {
  state = {
    text: 'hello world'
  }
  render() {
    return <div><h4>{this.state.text}</h4></div>
  }
}

ReactDOM.render(<App/>,document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

Is this a recommended way to initialize component state without wrapping it in a constructor?

ninjaas
  • 327
  • 5
  • 15
  • Its exactly the same thing I don't think there is a difference. In general, you should initialize state in the constructor that is recommended because the moment your component is then called constructor is the one who gets called immediatly. So its good to intialize the state in constructor. – Hemadri Dasari Jan 26 '18 at 14:05

1 Answers1

3

This is a proposal for class fields declarations in stage 3 at the moment.
It's basically doing the same thing behind the scenes.

babel will transpile it the same.

Giving these code examples:

class MyClass {
  state = {
    myVal: 'Hello world'
  }
}

And

class MyClass {
  constructor() {
    this.state = {
      myVal: 'Hello world'
    }
  }
}

Both will transpile to:

var MyClass = function MyClass() {
  _classCallCheck(this, MyClass);

  this.state = {
    myVal: 'Hello world'
  };
};

You can play with it yourself with these repl's constructor - fields.

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99