Why do some developers use constructor and super in their class in React.js?

Viewed 3112

I always use this expression in my components:

class Cart extends Component { }

Recently I have seen a lot of codes using this expression.

class Cart extends React.Component {
  constructor(props) {
    super(props);
  }
}

Why is it? What is the purpose of using constructor and super? Is React.Component and Component same? Why do we pass props in constructor and super? I am not asking what super and constructor are, I am asking difference between 2 codes above and benefits of using each one?

I checked online but did not see any explanation, just code examples.

4 Answers

Constructors and super are not react specific or even javascript specific. They are specific to the inheritance in OOP.

Constructors

Constructors are what can be called as initializing functions in a class. Let's look at an example where a constructor can be used.

class parentClass {
 constructor(){
   this.foo = foo;
   this.bar = bar;
}

function sharedMethod1(){
    print(this.foo);
}

function sharedMethod(){
    print(this.bar)
}
}

object1 = new ParentClass(foo1, bar1);

object1.sharedMethod1() // this will print foo1;
object1.sharedMethod2() // this will print bar1;

object2 = new ParentClass(foo2, bar2);
object2.sharedMethod1() // this will print foo2;
object2.sharedMethod2() // this will print bar2;

when there is a need to create multiple instances of a class with different values for member variables / functions, we make use of the constructor functions.

Super

The super keyword is used in inheritance as well. In inheritance when extending a child class from a parent class, there is a need to initialise the constructor of the parent class. The super keyword is used for this purpose. let's look at the below example for super.

class ParentClass (){
constructor(){
this.foo = foo;
}
} 

class childClass extends ParentClass(){
super(foo1); // super is used here initialize the constructor of the ParentClass
} 

The same principle mentioned above is followed in React as well. Please look into dan abramov's blog post on constructor and super here https://overreacted.io/why-do-we-write-super-props/

Dan Abramov mentions on his blog that:

You can’t use this in a constructor until after you’ve called the parent constructor. JavaScript won’t let you.

JavaScript enforces that if you want to use this in a constructor, you have to call super first.

calling super(props) is needed in order to access this.props.

as mentioned on this thread, there are 2 main reasons to use a constructor on a react component:

  1. Initializing local state by assigning an object to this.state.
  2. Binding event handler methods to an instance. If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

Copied from reactJS website.

If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Typically, in React constructors are only used for two purposes:

Initializing local state by assigning an object to this.state.
Binding event handler methods to an instance.

You should not call setState() in the constructor(). Instead, if your component needs to use local state, assign the initial state to this.state directly in the constructor:

Constructor is the only place where you should assign this.state directly. In all other methods, you need to use this.setState() instead.

Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead.

https://reactjs.org/docs/react-component.html

And here is the purpose of super() ,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super

I tried with babel, Here's what I get.

With Constructor I get this function,

class App extends React.Component{
    constructor(props){
     this.state = {}
    }
}

Related part in ES5,

var App =
/*#__PURE__*/
function (_React$Component) {
  _inherits(App, _React$Component);

  function App(props) {
    var _this;

    _classCallCheck(this, App);

    _this.state = {};
    return _possibleConstructorReturn(_this);
  }

  return App;
}(React.Component);

Without Constructor

class App extends React.Component{
    state = {}
}

ES5 code

var App =
/*#__PURE__*/
function (_React$Component) {
  _inherits(App, _React$Component);

  function App() {
    var _getPrototypeOf2;

    var _temp, _this;

    _classCallCheck(this, App);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _possibleConstructorReturn(_this, (_temp = _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(App)).call.apply(_getPrototypeOf2, [this].concat(args))), _this.state = {}, _temp));
  }

  return App;
}(React.Component);

Why is it? What is the purpose of using constructor and super?

Constructors and the super-keyword are not react specific, but JavaScript specific. Search for inheritance and "OOP" in JavaScript to better understand it (e.g. this medium article). super and inheritance is also not only bound to JavaScript, many other languages also use it and explain it accordingly, here for example is a good explanation of how the super-keyword should be used in java.

Why do we pass props in constructor and super?

Check Why Do We Write super(props)?.

Is React.Component and Component same?

Yes. In the head-section of the files are a bunch of import ...-statements. For React.Component you will find something like import * as React from "react" or import React from "react". In case of Component you will find import { Component } from "react". Check the import-documentation from MDN for more information.

I am asking difference between 2 codes above and benefits of using each one?

There is no difference in the result. Both versions work the same and there is no (notable) difference in performance. One version is shorter and less noisy. If you have no further instructions in the constructor, I would recommend suppressing it.

Related