In React, when using ES6 classes to create components, super()
and super(props)
are both used to call the constructor of the parent class. However, there is a difference between the two:
super()
This is used when we don’t need to access this.props
in the constructor of the child component. It simply calls the constructor of the parent component without passing any props to it.
class ChildComponent extends React.Component {
constructor() {
super();
// We can access this.props here if we want
}
}
super(props)
This is used when we need to access this.props
in the constructor of the child component. It calls the constructor of the parent component and passes the props to it.
class ChildComponent extends React.Component {
constructor(props) {
super(props);
// Now we can access this.props
}
}
In most cases, we will want to use super(props)
to make sure that this.props
is available in the constructor if we need it. However, if we are not using this.props
within the constructor, we can simply use super()
to call the parent constructor without passing any props.