what does super() do without any arguments?

In ES6, derived classes have to call super() if they have a constructor. In react, all components extend from the Component class.

You don’t actually need a constructor for every ES6/react class. If no custom constructor is defined, it will use the default constructor. For base classes, it is:

constructor() {}

And for derived classes, the default constructor is:

constructor(...args) {
  super(...args);
}

You also need to call super() before accessing this, since this is not initialized until super() is called.

There are a few reasons to use a custom constructor in react. One is that you can set the initial state within the constructor using this.state = ... instead of using the getInitialState lifecycle method.

You can also bind class methods inside the constructor with this.someClassMethod = this.someClassMethod.bind(this). It’s actually better to bind methods in the constructor since they will only be created once. Otherwise if you call bind or use arrow functions to bind methods anywhere outside the constructor (like in the render method), it will actually end up creating a new instance of the function on every render. Read more about that here.

If you want to use this.props in the constructor, you need to call super with props as an argument:

constructor(props) {
  super(props);
  this.state = {count: props.initialCount};
}

If you don’t, then this.props is undefined in the constructor. However, you can still access this.props anywhere else in the class outside the constructor without needing to do anything with it in the constructor.

Leave a Comment