Why do we write super(props)

Prashant Jha
2 min readMar 16, 2021

--

In JavaScript, super refers to parent class constructor. (In our case, it refers to React.Component).

JavaScript doesn’t allow us to use ‘this’ inside a constructor until after calling the parent class constructor.

Why JS enforces to run parent class constructor/calling super before touching `this` :-

Imagine a scenario calling super() after this.Intro(). Parent hasn’t set it’s name value yet and we are accessing this.name in Intro(). It will cause error.

So as in react to call any property or methods like componentDidMount of parent we have to call constructor of parent (Component or PureComponent) before using those methods or properties of parent in any methods or properties of child.

Why pass props :-

If we call super() without props arguments we can still access props in render() or other methods with this.props.

Because react also assigns props to the instance right after calling own constructor.

But calling super() without props arguments is still confusing because this.props would still be undefined between super call and end of constructor. It would be even more challenging if this happens in some methods that is called from constructor. And that’s why passing down super(props) is always recommended.

To ensure this.props is set even before the constructor exists.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Prashant Jha
Prashant Jha

Written by Prashant Jha

interested in Code, Books, Philosophy, Poems

No responses yet

Write a response