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.

Syntax

 
  1. Constructor(props){  
  2.      super(props);  
  3. }  

In React, constructors are mainly used for two purposes:

  1. It used for initializing the local state of the component by assigning an object to this.state.
  2. It used for binding event handler methods that occur in your component.

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.