constructor() in ReactJS

constructor() of the component is called when component is created. constructor() is called only once in the lifetime of component.

constructor() is the first method to be called in mounting phase of component. constructor() is called before component is mounted ( added to DOM ).

Why constructor() should be used?

There are two main purposes of using the constructor of a component in ReactJS.

Let us have a look at an example.


import React from 'react';
import ReactDOM from 'react-dom';

class Counter extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            clickCount: 0
        };
        this.onButtonClick = this.onButtonClick.bind(this);
    }
    onButtonClick(e){
        const { clickCount } = this.state;
        this.setState({
            clickCount: clickCount + 1
        });
    }
    render(){
        const { clickCount } = this.state;
        return (
            <div>
                <div>Total Count : { clickCount }</div>
                <button onClick={this.onButtonClick}>Increase counter</button>
            </div>
        );
    }
}

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

Open the above code in codepen.

In above code, constructor() initalizes state object of the component and binds onButtonClick method to the component ( We will see that later ). onButtonClick method will be called on event of onClick of the button.

Points to remember while using a constructor

There are many common mistakes that a developer does while using constructor in ReactJS. Below are some points that you should remember while using a constructor.

  • When you use a constructor, the fist thing you should call super(props) before any other statement.Otherwise this.props will be undefined which will lead to some bugs.
  • You should not call this.setState method in constructor ( which will call render ) method. Instead, you should use directly this.state object.
  • constructor is only place where this.state can be used. In every other function, you should use this.setState method.
  • Do not call any API or do any other things in constructor. You can use componentDidMount() for that.
  • Do not copy props to state. That will create bugs (update to props will not update state ).

constructor(props){
    super(props);
    this.state = {
        clickCount: props.clickCount
    };
    this.onButtonClick = this.onButtonClick.bind(this);
}
                    

Here is the tutorial on setState()

Conclusion

In this section, we learned about constructor and for what it can be used.
In the next section, you will learn about getDerivedStateFromProps() of ReactJS component.