Easy Tutorial
❮ React Tutorial React Lists And Keys ❯

React constructor() Method

React Component Lifecycle

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:

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.

React Component Lifecycle

❮ React Tutorial React Lists And Keys ❯