/    /  ReactJS- Constructor

Constructor

 

A React constructor is a method that is called automatically when we generated an object from that class. It can manage initial initialization tasks such as defaulting certain react object properties or sanity testing the arguments passed in. Simply placed, the react constructor is a method that helps in the creation of objects. 

 

The react constructor is no different in React. This can connect event handlers to the react component and/or initialize the component’s local state. Before the react component is mounted, the constructor() function is shot, and, like most things in React, it has a few rules that you can follow when using them.

 

Step 1: Call super(props) before using this.props

Due to the nature of the react constructor method, this.props object is not accessible straight out of the gate, which can lead to errors. An error will be thrown by this react constructor:

constructor() {
 console.log(this.props);
}

 

Instead, we transfer the value of a props to the super() function from the react constructor() method:

constructor(props) {
 super(props);
 console.log(this.props);
}

 

When you call the react super() function, the parent class constructor is called, which is in the case of a React is React.Component. 

 

Step 2: Never call setState() inside constructor()

The react constructor of your UI component is the ideal place to set the component’s initial state. You must set the initial state directly, rather than using react setState() as you can in other methods in your class:

constructor(props) {
 super(props);


 this.state = {
   name 'kapil',
   age: 22,
 };
}

 

The only place you can assign the local state directly like that is the react constructor. You should depend on react setState() somewhere else inside our UI component instead.

 

Step 3: Avoid assigning values from this.props to this.state

You should try to avoid setting values from the react properties when setting the initial UI component state in the react constructor. We can do the following:

constructor(props) {
 super(props);


 this.state = {
   name: props.name,
 };
}

 

Step 4: Bind events all in one place

constructor(props) {
 super(props);


 this.state = {
   // Sets that initial state
 };


 // Our event handlers
 this.onClick = this.onClick.bind(this);
 this.onKeyUp = this.onKeyUp.bind(this);
 // Rest Code
}