fahmisan
fahmisan

Reputation: 43

Why do we need to call super(props) and how does it work in React?

I have a basic knowledge of JS and now exploring react. I know there are lots of answers to what is super(props) and when to use it in react.

But there is yet answers to HOW it works and WHY do we call super(props) in constructor in React?

Upvotes: 1

Views: 1011

Answers (1)

Enmanuel Duran
Enmanuel Duran

Reputation: 5118

first of all it's important to understand that you will only call super(props) in a component if you need to use the props inside a constructor for a particular reason, by making use of super(props) you're enabling access to your component's props inside of the constructor.

If you don't really need to use props there, you could just use super(), however, it's recommended to use super(props) to avoid inconsistencies and missleading behaviors.

The constructor is executed before components are mounted and sometimes you want to use them to set up some things like React's local state, or bind some handlers.

There are other references to this topic in SO that could help you clarify your doubts:

Upvotes: 3

Related Questions