11

Suppose I've the following class:

class Tabs extends React.Component {
  displayName: Tabs;

  static propTypes = {
  selected: React.PropTypes.number,
  children: React.PropTypes.oneOfType([
    React.PropTypes.array,
    React.PropTypes.element
  ]).isRequired
  };

  constructor() {
  super();
  this.state = {
    selected: 0,
    maxSelected: 0
  };

  render() {
    return(
      <div>
       {this.props.selected}
       {this.props.children}
      </div>
    );
  }
};

I want to know that if passing the following constructor is important:

constructor(props) {
  super(props);
}

My current code works just fine but I wanted to know if this is a good practice.

Nirmalya Ghosh
  • 2,298
  • 3
  • 18
  • 33
  • No it's not, in fact there's even an eslint rule to disallow this http://eslint.org/docs/rules/no-useless-constructor – azium Mar 07 '16 at 03:50
  • 1
    Possible duplicate of [What's the difference between "super()" and "super(props)" in React when using es6 classes?](http://stackoverflow.com/questions/30571875/whats-the-difference-between-super-and-superprops-in-react-when-using-e) – XML Feb 08 '17 at 12:35

1 Answers1

27

According to Sophie Alpert with the React team it's only necessary to pass props into the constructor if you intend on using this.props inside the constructor. After the constructor is invoked, React attaches the props to the component from the outside.

Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238
Rick Runyon
  • 4,204
  • 1
  • 17
  • 15
  • I'm new to react, are you saying like. If im going to use props in my current component, in that case only I need to use super(props) in constructor?? – Gopi P Oct 09 '19 at 15:57
  • 4
    @usama super(props) is unnecessary in constructor until unless you're gonna do some work in the constructor level. In ES2015every class has default constructor so it's unnecessary to have empty one. – Gopi P Nov 06 '19 at 09:13