Understanding Constructors With React Components

Read it in 8 Mins

Last updated on
07th Jun, 2022
Published
10th Dec, 2021
Views
6,568
Understanding Constructors With React Components

The React Constructor is a method that’s automatically called during the creation of an object from a class. Simply put, the constructor, like its name, is a great tool to build things. Click here to understand more about usereducer used in React. 

Constructors are used for two key objectives:

  • To initialize the local state of the component by assigning an object to this.state
  • To bind event handlers that occur in the component

In this blog, we’ll take you through all you need to understand about React constructors including the rules to be followed while implementing them. We will also look at how to bind events all in one place and take note of how to assign values accurately.

What is a Constructor?

In a class, a constructor is a method that is automatically called when an object of that class is created. Typically, this is how it works:

Syntax:

Constructor(props){ 
    super(props);   
}

A couple of points to note about a constructor are:

  1. It is not necessary to have a constructor in every component.
  2. It is necessary to call super() within the constructor. To set property or use 'this' inside the constructor it is mandatory to call super().

We must remember that the setState() method cannot be used directly in the constructor(). Use 'this.state' to assign the initial state in the constructor. The constructor uses this.state to assign initial state, and other methods should use set.state().

Call super(props) Before Using this.props

In React, the constructor is called during component creation and before mounting. If you want to implement the constructor for a React component, call the super(props) method before any other statement. Otherwise, this. props will be undefined in the constructor and create bugs.

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

Using super(props) is simple. We just have to call it in the constructor method of our child component:

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

Never Call setState() Inside constructor()

The constructor is the ideal place to set up your component's initial state. Instead of using setState() in other methods, you will need to assign the initial state directly.

class Hello extends React.Component { 
   constructor(props) { 
   super(props); 
   this.setState({ 
  title: 'This is the first test' 
   }); 
}   
  render() { 
    return <div>{this.state.title} </div> 
  } 
}   
ReactDOM.render(<Hello />, document.getElementById('container'));

When you use the setState() method in React, it does more than just assign a new value to this. state. It also re-renders the component and all its children. Additionally, if you are trying to update a class that was defined inside of a constructor, you will receive an error, so we should avoid setState() in constructors because it is the only place we directly assign the initial state to this.state.

constructor(props) { 
 super(props); 
 this.state = { 
   name 'kapil', 
   age: 22, 
 }; 
}

When creating a component, you should avoid setting values directly from the component's properties. Do it as follows:

constructor(props) {
 super(props);
 this.state = {
   name: props.name,
 };
}

If you try to change the name property in the state object, it will not work. If you want to modify this property later, you should not use setState(). Instead, access the name property directly in your code by using this.props. name instead of assigning it directly to the state.

Bind Events All in One Place

In the constructor, you can bind event handlers easily:

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 
}

Avoid Assigning Values from this.props to this.state

It might be tempting to set the component's state right away, but this could cause a few issues. One issue is that you can't really test it properly until the API call has been made and the response received. Another reason to avoid setting state in the constructor is that you don't need to worry about that value again once it's been defined.

While this may seem the obvious approach, the constructor function is not always the right place to do API calls. If your component relies on another state that is available in its parent or grandparent components, then you may want to consider making API calls in componentDidMount(). This way you don't need to make API calls multiple times.

constructor(props) { 
  super(props);   
  this.state = { 
   Reptile: 'Alligator', 
  }; 
}

Do You Even Need a Constructor?

React components have a useful feature as constructors. Constructors are difficult to manage. Don’t define the constructors if the state in the components would not be maintained. React applications are built using functional components and if state or event handlers are not required then it is better not to have the class components.

Arrow Functions

Arrow functions make it possible to write more concise code, and they also help you to use the ‘this’ binding correctly. If you're using arrow functions, then you don't need to bind any event to 'this'. The scope of 'this' is global and not limited to any calling function.

import React, { Component } from 'react';
class App extends Component {   
  constructor(props){   
    super(props);   
    this.state = {   
         data: 'ABC'   
      }   
  }   
  handleEvent = () => {   
    console.log(this.props);   
  }   
  render() {   
    return (   
      <div className="App">   
    <h2>React Constructor Example</h2>   
    <input type ="text" value={this.state.data} />   
        <button onClick={this.handleEvent}>Please Click</button>   
      </div>   
    );   
  }   
}   
export default App;

The use of a constructor

1) Initialization of the state constructor

class App extends Component {   
  constructor(props){   
        // here, it is setting initial value for 'inputTextValue'   
        this.state = {   
            inputTextValue: 'initial value',   
        };   
  }   
}

2) The way to use 'this' inside the constructor

class App extends Component {   
    constructor(props) {   
        // when you use 'this' in constructor, super() needs to be called first   
        super();   
        // it means, when you want to use 'this.props' in constructor, call it as below   
        super(props);   
    }   
}

3) Initialization of third-party libraries

class App extends Component {   
    constructor(props) {  
        this.myBook = new MyBookLibrary(); 
        //Here, you can access props without using 'this'   
        this.Book2 = new MyBookLibrary(props.environment);   
    }   
}

4) Binding some context(this) when we need a class method to be passed in props to children.

class App extends Component { 
    constructor(props) {   
        // when you need to 'bind' context to a function   
        this.handleFunction = this.handleFunction.bind(this);   
    }   
}

Example Program:

React Component with Constructor

index.js 
import React from 'react'; 
import ReactDOM from 'react-dom'; 
class Main extends React.Component { 
  constructor() { 
    super(); 
    this.state = { 
      planet: "Earth" 
    } 
  } 
  render() { 
    return ( 
      < h1 >Hello {this.state.planet}!</h1> 
    ); 
  } 
} 
ReactDOM.render(<Main />, document.getElementById('root')); 

Output: 

Hello Earth! 

React Component without Constructor 

Index.js 
import React from 'react'; 
import ReactDOM from 'react-dom'; 
class Main extends React.Component { 
  state = { 
    planet: "Mars" 
  } 
  render() { 
    return ( 
      < h1 >Hello {this.state.planet}!</h1> 
    ); 
  } 
} 
ReactDOM.render(<Main />, document.getElementById('root')); 

Output: 

Hello Mars! 

Constructor vs getInitialState

The constructor and getInitialState in React are used to initialize state and they can’t be used interchangeably. The main fundamental difference between ES5 and ES6 is in the new class keyword. ES5 didn't provide the convenience of defining the React component as classes however ES did provide the convenience to define react component as class 

getInitialState is the ES5 friendly method to define the initial state of a React component. We use getInitialState with React.createClass and constructor is used with React.Component. 

For example

 class Goodmorning extends React.Component { 
  render() { 
    return <span>Good Morning</span>; 
  } 
}
It would rely on helper module called create-react-class: 
var createGoodmorningReactClass = require('create-react-class'); 
var Goodmorning = createReactClass({ 
  render: function() { 
    return <span>Good Morning</span>; 
  } 
}); 
The object passed into create-react-class that is defined in initial stage by calling the getInitialState attribute: 
 var Goodmorning = createReactClass({ 
  getInitialState: function() { 
    return {name: this.props.name}; 
  }, 
  render: function() { 
    return <span>Good {this.state.name}</span>; 
  } 
}); 
In ES6 implementation: 
class Goodmorning extends React.Component { 
  constructor(props) { 
    super(props); 
    this.state = { 
      name: props.name 
    } 
  } 
  render() { 
    return <span>Good {this.state.name}</span>; 
  } 
} 

Does the Constructor Remain Relevant? 

React is an extremely powerful JavaScript Framework. Understanding how well its component lifecycle works would help to unlock the potential and power of the React JavaScript Framework.  

As we have seen in this blog, as you build React components, the constructor is one of the features that isnt supported in functions.  

A constructor lets you define variables and initialize them with default values for the sake of convenience. However, if there is no state initialization or method binding, we do not need to define a constructor for a component in JavaScriptAs illustrated in this case, we would not fetch data from the constructor and neither would binding methods be necessary to set the initial state. Like they say, it’s important to know the rules to know which ones can be broken. It’s a good method to learn about for when you might want to create several instances of a class with varying values for member functions.  

Profile

Rajesh Bhagia

Blog Author

Rajesh Bhagia is experienced campaigner in Lamp technologies and has 10 years of experience in Project Management. He has worked in Multinational companies and has handled small to very complex projects single-handedly. He started his career as Junior Programmer and has evolved in different positions including Project Manager of Projects in E-commerce Portals. Currently, he is handling one of the largest project in E-commerce Domain in MNC company which deals in nearly 9.5 million SKU's.

In his role as Project Manager at MNC company, Rajesh fosters an environment of teamwork and ensures that strategy is clearly defined while overseeing performance and maintaining morale. His strong communication and client service skills enhance his process-driven management philosophy.

Rajesh is a certified Zend Professional and has developed a flair for implementing PMP Knowledge Areas in daily work schedules. He has well understood the importance of these process and considers that using the knowledge Areas efficiently and correctly can turn projects to success. He also writes articles/blogs on Technology and Management

Develop the skills of the future via outcome-based immersive learning

Speak to our Career Advisor now!

Select
Your Message (Optional)