DEV Community

Cover image for Constructor is no more | React
Ashish Singh Rawat
Ashish Singh Rawat

Posted on

Constructor is no more | React

Yes, you read it right! There is no more constructor in class component in react.js. You must have seen the traditional react code similar to below


class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      toggle: true,
    };
  }
}

Enter fullscreen mode Exit fullscreen mode

as per new react(v0.13.0-beta), this can be written in a new format


class App extends Component {
    state = {
      toggle: true,
    };
}

Enter fullscreen mode Exit fullscreen mode

This was inspired by TypeScript’s property initializers.

Advantages:

  • Much cleaner way to write

References

Top comments (2)

Collapse
 
007_dark_shadow profile image
Asif Vora

So, how can we set props value in default state.

Collapse
 
ashish9342 profile image
Ashish Singh Rawat

class yourComponent extends React.Component {
state = {
x: this.props.initialX,
// You can even call functions and class methods:
y: this.someMethod(this.props.initialY),
};
}