Javatpoint Logo
Javatpoint Logo

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

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.

Example

The concept of the constructor can understand from the below example.

App.js

Main.js

Output

When you execute the above code, you get the following output.

React Constructor

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).

Arrow Functions

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.






Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA