Constructor | Lifecycle

lets see how to initialize state of a component using constructor

In React realm mounting refers to the loading of components on the DOM. This phase contains a set of methods which get invoked when the component is getting initialized, and loaded on to the DOM.

The methods which get called are as follows:

  • constructor This is the first method that gets called whenever a component is created. The constructor is called only once in the whole lifecycle of a component. It’s used to set up the initial values of variables and component state.

class ContraMusicPlayer extends React.Component
constructor(props) {
  super(props);
  this.state = {
    volume: 70,
    status: 'pause'
  }
}

Usage: Setup the initial state of the component.

If we render the above component as <ContraMusicPlayer/> it will by default render with volume level at 70 and it will be in the paused state.

In React’s realm the constructor is the only place where this.state should be used. Every other method should update the state using this.setState()

One of the best use of constructor is to define the initial state of the component, which is very useful for any react application. We can also bind any event that occurs in our component in the constructor like the following.

constructor(props){
    super(props);
    this.state = {} // state object 
    this.handleEvent = this.handleEvent.bind(this);
 }

In above’s example, the event will fire after the user has clicked the button or keyup, blur or any other event and then we need to set up the context to its parent and not the child context, so we are binding this to parent. Let me take one example to simplify this explanation.

Example

// App.js

import React, { Component } from 'react';

class App extends Component {
  constructor(props){
    super(props);
  }
  handleEvent(){
    console.log(this.props);
  }
  render() {
    return (
      <div className="App">
        <button onClick={this.handleEvent}>Please Click</button>
      </div>
    );
  }
}

export default App;

Now, if you run this and see in the console, then it says like this. Uncaught TypeError: Cannot read property 'props' of undefined

That means it can not find this as a global pointer or keyword or object to the component, it finds as that function property this, not a component property.

So, we need a solution to that. Make one new file, called app1.jsx in the src folder and put the code like this.

import React, { Component } from 'react';

class App1 extends Component {
  constructor(props){
    super(props);
    this.handleEvent = this.handleEvent.bind(this);
  }
  handleEvent(){
    console.log(this.props);
  }
  render() {
    return (
      <div className="App">
        <button onClick={this.handleEvent}>Please Click</button>
      </div>
    );
  }
}

export default App1;

Now, include this file in the main.js.

// main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/app.jsx';
import App1 from './app/app1.jsx';

ReactDOM.render(<App />, document.getElementById('App'));

And in above code, just replace the following line.

ReactDOM.render(<App />, document.getElementById('App'));

with this line

ReactDOM.render(<App1 />, document.getElementById('App1'));

Now, again run, you can see an empty object in the console. So now, this is pointing to the global context of the React component.

Following example will not working because, I have not use app1.jsx. You can use app1.jsx and modify the main.js as I have mentioned earlier.

Then see in the console, you can find empty object, if you got any error, then please check again the code, you might not have imported app1.jsx in the main.js.

So, we can achieve two purposes with the constructor function.

  1. Set the initial state of the component

  2. Point the global context of this keyword.

Arrow Functions

If you are using arrow functions then, you do not need to bind any event to this. In that scenario, this scope is global and not limited to any calling function. So If you are using ES6 syntax, then it is best practice to use Arrow Function

import React, { Component } from 'react';

class App2 extends Component {
 constructor(props){
   super(props);
 }
 handleEvent = () => {
   console.log(this.props);
 }
 render() {
   return (
     <div className="App">
       <button onClick={this.handleEvent}>Please Click</button>
     </div>
   );
 }
}

export default App2;

Last updated