5

I've seen many code snippets such as HelloWorld, where props is passed to super(). What is the reason to do that when this.props is not accessed in the constructor?

class HelloWorld extends Component {
    constructor(props) {
        super(props);

        this.state = { message: 'Hi' };
        this.logMessage = this.logMessage.bind(this);
    }

    logMessage() {
        console.log(this.state.message);
    }

    render() {
        return (
            <input type="button" value="Log" onClick={this.logMessage} />
        );
    }
}
Abraham
  • 8,525
  • 5
  • 47
  • 53
j.doe
  • 1,214
  • 2
  • 12
  • 28
  • 1
    There is no reason really. If you're not using `this.props` in the constructor, all you need to do is call `super()`. The `Component` superclass will setup props just fine, they just won't be accessible inside the constructor. – Andrew Li Sep 04 '18 at 03:29

3 Answers3

1

The constructor for a React component is called before it is mounted. When implementing the constructor for a React component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Read Here for more details.

Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
1

If you're not going to use this.props in your constructor, you don't have to put it into super() like this:

constructor(){
   super();
   this.state = { randomState: "" };
   this.randomProperty = null;
}

But, in some cases, props passed from the parent component can be accessed and used inside constructor for initializing state (these props are not affected by prop change). By passing props to super, you can now use this.props inside constructor.

constructor(props){
   super(props);
   this.state = { randomVar: props.initialValue, propDependentState: this.props.someValue };
   this.someVar = props.defaultValue;
   this.anotherVar = this.props.openToChangesProp;
}

Take note that those props that are directly passed to this component are the only props accessible to the constructor. props that are mapped from state using redux connect is included in the props that can't be accessed here since the component hasn't mounted yet.

sdabrutas
  • 1,477
  • 2
  • 14
  • 28
0

You don't have to do super(props). That is done only to access props inside the constructor. You can write:

constructor(){
 super()
 this.state={}
}

If you do not pass super(props):

 constructor(props){
  super()
  console.log('this.props', this.props); // => undefined
  console.log('props', props); // => whatever the props is
 }

Refer this stackoverflow answer

illiteratewriter
  • 4,155
  • 1
  • 23
  • 44