Why Do We Write super(props) in React JS?
Why do we call super? Can we not call it? If we have to call it, what happens if we don't pass props?
Let's find out.
Imagine using this before super call was allowed. A month later, we might change bark to include the Animal's name in the message:
But we forgot that this.bark() is called before the super() call had a chance to set up this.name. So this.name isn't even defined yet! As you can see, code like this can be very difficult to think about.
This leaves us with another question: why pass props?
You might think that passing props down to super is necessary so that the base React.Component constructor can initialize this.props
So even if you forget to pass props to super(), React would still set them right afterwards. There is a reason for that.
When React added support for classes, it didn't just add support for ES6 classes alone. The goal was to support as wide range of class abstractions as possible. It was not clear how relatively successful would ClojureScript, CoffeeScript, ES6, Fable, Scala.js, TypeScript, or other solutions be for defining components. So React was intentionally unopinionated about whether calling super() is required â€” even though ES6 classes are.
So does this mean you can just write super() instead of super(props)?
Probably not because it's still confusing. Sure, React would later assign this.props after your constructor has run. But this.props would still be undefined between the super call and the end of your constructor:
It can be even more challenging to debug if this happens in some method that's called from the constructor. And that's why I recommend always passing down super(props), even though it isn't strictly necessary:
This ensures this.props is set even before the constructor exits.
With Hooks, we don't even have super or this. But that's a topic for another day.