ReactJS: What are some criteria for not needing a constructor in a component class?

205 views Asked by At

I want to know the conditions where by a constructor is not needed in a component's class declaration. I figure it is for stateless components, but are there any other reasons? Would not having any functions inside the component (besides life cycle functions) be one, for example?

3

There are 3 answers

0
Amid On BEST ANSWER

I think it would be appropriate to just leave here an excerpt from react docs (emphasis mine):

The constructor is the right place to initialize state. If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.

0
Fez Vrasta On

You don't actually need a constructor at all in any case if you use the babel stage-2 preset, because it provides the class properties that effectively replace its usage:

class Component extends React.Component {
  constructor() {
    this.state = {};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() { console.log('click'); }
}

becomes

class Component extends React.Component {
  state = {};
  handleClick = () => console.log('click');
}

Ignoring this, a constructor is needed only if you need to bind component methods to its context, or if you need to initialize the state property.

Another case is if you need to do something with the this.props class property, but this is considered an anti-pattern by React.

class Component extends React.Component {
  constructor() {
    this.state = {
      // don't do this! anti-pattern! duplication of source of truth!
      duplicatedState: this.props.myName,
    };
  }
}
0
Peter On

I usually only add a constructor if the component has a internal state I need to set up before it is used, otherwise I leave out the constructor. Having functions in the component doesn't affect my decision in this regard