5

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.

5
  • 3
    Possible duplicate of What's the difference between "super()" and "super(props)" in React when using es6 classes? Commented Jun 7, 2019 at 22:48
  • 1
    Now with new es6 you don’t have to use constructor and super. However some people are used to old fashion way Commented Jun 8, 2019 at 0:01
  • @AlexanderStaroselsky not quite a duplicate, but the answer is functionally the same. The answer in the other thread should be referenced here. Commented Jun 8, 2019 at 0:11
  • Here's my opinion although I'm not a JS object model freak. React.Component and Component are the same reference i.e. the same thing, they just differ in usage based on how you import them in your code. If you import React only then you would have to use React.Component else you manually destructure { Component } and then use it direct. You pass props to super because you are extending to Component which becomes your super class to which you are passing props to but constructor method itself is optional when you dont have any declarations in it. Commented Jun 8, 2019 at 0:53
  • So, you can also use functional component like: const MyComponent = (props) =>{...} it's more short and quickly Commented Jun 8, 2019 at 9:24

4 Answers 4

2

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

That blog is for outdated es6. In new es7 there is no need to use constructor or super. reactnative.guide/6-conventions-and-code-style/…
Perhaps, I haven't got a chance to learn about ES7 yet. still, I believe it answers OP's question
He is asking about difference between those two which is one is written on es6 and the other one in es7. Both of them are correct though. Please click on the link I have provided in my answer to read more about es7
Yeah, I just learned about it here, thanks for the information!
1

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);

1 Comment

can you provide link to this
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.