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?
-
Did you search before asking this? https://stackoverflow.com/questions/38712524/when-to-use-constructors-in-react-components – StudioTime Sep 21 '17 at 14:51
-
1Possible duplicate of [When to use constructors in React components?](https://stackoverflow.com/questions/38712524/when-to-use-constructors-in-react-components) – StudioTime Sep 21 '17 at 14:51
-
It partially answers my question. I am wondering if there are any other reasons besides a lack of internal state though. For instance, if your component is stateless but also has some functions declared (not lifecycle functions), would you need a constructor? – connected_user Sep 21 '17 at 14:53
-
The question should be when you *do need* a constructor. Unless you have to set the state or bind some methods (s.t. you don't bind them at render time) or any other thing that you would possibly need, you don't have to write it. It doesn't help with anything if it's just there doing nothing. @connected_user: to answer above comment: no – Raul Rene Sep 21 '17 at 14:53
3 Answers
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.

- 21,508
- 5
- 57
- 54
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

- 1,006
- 7
- 15
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,
};
}
}

- 14,110
- 21
- 98
- 160