I’d like to understand it either. I noticed that the “constructor” is used only when declaring a state. There is no “constructor” in stateless components for some reason. I didn’t find any explanation about that. Could anyone explain it please?
I thought, not writing a constructor explicitly is the same as writing a constructor as the following:
constructor(props) {
super(props);
}
When inheriting a class in JavaScript, if we don’t provide an extended class with a constructor, the constructor of the parent class will be called.
When we want to declare a state property in the constructor, I thought, first we need to write the default constructor as above explicitly and then add the declaration of the state property. So this was not confusing at all to me.
But on the other hand, I’m interested in whether the parameter props are really needed and what happens if we don’t include super(props). I think that, in those cases, the class would lose accesses to most of the features of React Component, but I don’t know yet. If there is a chance in the future exercises, I would like to try these things and report the results.
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.
Is there no problem if we don’t use props? It seems, depends on codes. If we don’t pass props to the constructor, like this:
constructor() {
super();
...
}
then undefined is passed to the constructor of the parent class. It is up to the code whether it causes an error. Furthermore, after an instance is created, it seems React automatically assigns props on the instance. So it is not really needed to pass props to super(). I have read the following articles about these things: