mounting

Mounting relates to adding nodes to the DOM.

When an instance of a component is created and inserted into the DOM, the following methods are called (in this order):

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

constructor()

You do not need to implement a constructor for a React component if you don’t initialise state and don’t mind methods.

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

React constructors are usually used for two reasons:

  • initialising local state by assigning an object to this.state
  • Binding event handler methods to an instance

Do not call setState() in the constructor(). If a component needs to use local state, assign the initial state to this.state directly in the constructor:

constructor(props) {
super(props);
this.state = { counter:0 };
this.handleClick = this.handleClick.bind(this);
}

Constructor is the only place where you should assign this.state directly. In all other methods, you need to use this.setState() instead.

render()

The render() method is the only required method in a class component.

When you call render(), it should examine this.props and this.state and return one of these types:

  • React elements
  • Arrays and fragments
  • Portals
  • Strings and numbers
  • Booleans of null

render() should be pure. This means that it should not modify component state, return the same result each time that it’s invoked and does not directly interact with the browser.

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialisations that require DOM nodes should go here.