React constructor() Method
The constructor() method format is as follows:
constructor(props)
Before a React component mounts, its constructor function is called.
When implementing the constructor in a subclass of React.Component, super(props)
should be called before any other statement.
The following example demonstrates how React calls the constructor when creating a component:
Example
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritewebsite: "tutorialpro"};
}
render() {
return (
<h1>My Favorite Website {this.state.favoritewebsite}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
In React, the constructor is only used for the following two purposes:
- Initializing the internal state by assigning an object to
this.state
. - Binding event handler methods to the instance.
If you do not need to initialize state or bind methods, you do not need to implement a constructor for your React component.
Do not call setState()
within the constructor function. If your component needs to use internal state, assign the initial state directly to this.state
within the constructor:
constructor(props) {
super(props);
// Do not call this.setState() here
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
You can only assign values to this.state
directly in the constructor. For assignments in other methods, you should use this.setState()
instead.