NST Infotech

Web development online courses

  • Home
  • About
  • Tutorials

July 13, 2019 by Sarfaraz Kasmani Leave a Comment

Difference between super() and super(props) in the constructor of a React Class Component?

Difference between super() and super(props) in the constructor of a React Class Component?

When creating Class Components in React, we often call super in the constructor of the Component and also pass in props to it. But do we really need to do this? I mean pass props to super.

Well, React Documentation recommends —

Class components should always call the base constructor with props.

and ES6 Classes have to call super if they are subclasses.

But why pass props to super? It’s because if we want to use this in the constructor, we need to pass it to super.

class MyComponent extends React.Component {
  constructor(props) { 
    super();
    console.log(this.props); // undefined
    console.log(props); // defined
  }
render() {
    return <div>Hello {this.props.message}</div>; // defined
  }
}

However, if we use super(props)

class MyComponent extends React.Component {
  constructor(props) { 
    super(props);
    console.log(this.props); // props will get logged.
  }
render() {
    return <div>Hello {this.props.message}</div>; // defined
  }
}

So, to conclude, If you want to use this.props inside the constructor, you need to pass it in super, otherwise, it’s okay to not pass props to super as we see that irrespective of passing it to super, this.props is available inside render function.

Please check the below video where I have explained the difference between super() and super(props). please like share and comment and do subscribe to my channel

0
SHARES
ShareTweet

Filed Under: Reactjs Tagged With: constructor, props, react, reactjs, super, super(props), this.props

About Sarfaraz Kasmani

Having more than 7 years of experience in the field of Front End Development. I love to teach!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

About me

I am Sarfaraz Kasmani a Front End Developer from Mumbai, India. I am having more than 7 years of experience in the field of Front End Development. I blog about Front End Development tips at this blog nstinfotech.com. Contact me or learn more about me from this page. Read More…

Recent Posts

  • Difference between super() and super(props) in the constructor of a React Class Component?
  • How to buy a domain and hosting from GoDaddy
  • Remove query strings from static resources wordpress

Archives

Categories

Connect Online

  • Facebook
  • LinkedIn
  • Twitter
  • YouTube

© 2019 · NST Infotech