Why does react class component always need to call super(props) in its constructor?

  • A+
Category:Languages

In the tutorial published by reactjs.org, it was stated that "Class components should always call the base constructor with props". In my own research, it seems that super(props) can be replaced by super() if this.props is not used in the constructors, according to this StackOverflow answer.

Therefore, my question is, why should we always pass in props to base constructor in reactjs? Is the advice sound? Why is it sound (or not sound) advice?

P.S. A screenshot is uploaded to this question just in case the original tutorial is updated while this question is being answered.

Why does react class component always need to call super(props) in its constructor?

 


Although it is suggested to pass props to super but it isn't strictly necessary.

Passing it just helps in an odd situation where you might have a called a method in constructor and then at some point of time in future decided to use props in it. Now since props aren't available in the constructor since you haven't passed props to super, it would result in an error. This kind of situation might be tricky to debug and hence its recommended to pass props always whenever you write a constructor so that it ensures this.props is set even before the constructor exits.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: