What is Constructor?
The constructor is a method used to initialize an object's state in a class. It automatically called during the creation of an object in a class.
The concept of a constructor is the same in React. The constructor in a React component is called before the component is mounted. When you implement the constructor for a React component, you need to call super(props) method before any other statement. If you do not call super(props) method, this.props will be undefined in the constructor and can lead to bugs.
In React, constructors are mainly used for two purposes:
Note: If you neither initialize state nor bind methods for your React component, there is no need to implement a constructor for React component.
You cannot call setState() method directly in the constructor(). If the component needs to use local state, you need directly to use 'this.state' to assign the initial state in the constructor. The constructor only uses this.state to assign initial state, and all other methods need to use set.state() method.
The concept of the constructor can understand from the below example.
When you execute the above code, you get the following output.
The most common question related to the constructor are:
1. Is it necessary to have a constructor in every component?
No, it is not necessary to have a constructor in every component. If the component is not complex, it simply returns a node.
2. Is it necessary to call super() inside a constructor?
Yes, it is necessary to call super() inside a constructor. If you need to set a property or access 'this' inside the constructor in your component, you need to call super().
When you run the above code, you get an error saying 'this' is not allowed before super(). So if you need to access the props inside the constructor, you need to call super(props).
The Arrow function is the new feature of the ES6 standard. If you need to use arrow functions, it is not necessary to bind any event to 'this.' Here, the scope of 'this' is global and not limited to any calling function. So If you are using Arrow Function, there is no need to bind 'this' inside the constructor.
We can use a constructor in the following ways:
1) The constructor is used to initialize state.
2) Using 'this' inside constructor
3) Initializing third-party libraries
4) Binding some context(this) when you need a class method to be passed in props to children.