
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
Leave a Reply