Lifecycle Methods

In React, every component has a lifecycle! From when it is instantiated to when it is unmounted from the DOM. We can hook up to each stage by employing special methods and performing specific actions at different stages of each component's lifecycle.

The lifecycle methods are declared in the React Component class. React automatically calls these methods at certain times during the "life" of a Component.

Here are the most commonly used ones (but there are more):

  • componentWillMount(): invoked immediately before the component is inserted into the DOM.
  • componentDidMount(): invoked immediately after the component is inserted into the DOM.
  • componentWillUnmount(): invoked immediately before a component is removed from the DOM.

In fact, the constructor and the render methods are also considered lifecycle methods!

The image above is a screenshot from interactive react lifecycle methods diagram.

The componentDidMount() is the (lifecycle) method which is commonly used to read data from an external API.

componentDidMount() {
  axios
    .get("url-to-some-api-endpoint")
    .then((response) => { /* update the state */ })
    .catch((err) => console.log(err));
}
Resources