How to use Constructor in React component

The blog provides the usage of Constructor in React Application. The concept of Constructor in React is similar to what we implement in other languages like C++ , Java.

What is a Constructor in React ?

The Constructor can be defined as given below

  • The constructor is used to initialize an object’s state
  • The constructor is invoked when an object is created in the class
  • The constructor is called in React when a component is mounted
  • The constructor is called using super(props)
  • this.props remains undefined if super(props) is not called in the class

How React uses constructor ?

  • Initialize the local state by assigning an object to this.state
  • Binds Event handler methods to an instance

How State should be initialized in the constructor() ?

  • The Constructor should not be called this.setState() in the constructor
  • We should use this.state to initialize the local state in the constructor

When constructor should be used in React Component ?

Usage of Constructor is not mandate for all the React Component. Constructor helps to initialize the object state before it is actually being accessed / modified. That is , when we need to set a object property or to access the object local state , then constructor should be called using super(props). 

If the super(props) is not defined in the constructor and program try to access the object value using this.props , then React will throw the error ->  ‘this’ is not allowed before super().

class App extends Component {  
    constructor(props){  
        // wrong assignment, super(props) is not defined
        this.siteName = "www.oracleappshelp.com";  
    }  
    render () {  
        return (  
            <p> Site Name : { this.props.siteName }</p>  
        );  
    }  
}
class App extends Component {  
    constructor(props){ 
      // correct  assignment                
		super(props);
        this.siteName = "www.oracleappshelp.com"; 
    }  
    render () {  
        return (  
            <p> Site Name : { this.props.siteName }</p>  
        );  
    }  
}

this.props will be undefined in the Cosntructor if super(props) is not called.

Use Constructor to bind functions in React Component

The constructor in React Component is useful when we need to bind functions as per below given example . The button clickSubmit is binded using this

constructor(props) {
  super(props);
  this.state = { count: 0 };
  this.clickSubmit = this.clickSubmit.bind(this);
}