ReactJS Component life cycle

We can declare special methods on the component class to run some code when a component mounts and unmounts also called lifecycle methods.

A ReactJS component goes through the following phases: initialization, mounting, updating and unmounting.

constructor() – Not a lifecycle method exactly.

State should usually be assigned in the constructor as it is used to set the initial state of our component. You can directly set the state property inside the constructor as setState method is not available before the component
is mounted.

componentWillMount()

This was deprecated in post React 17.0. If you still continue using this, you should use UNSAFE_componentWillMount().

render()

Rendering happens when the component mounts or updates. It has to be pure i.e. it cannot modify the state using setState. It should only handle the rendering of your component to the UI.

componentDidMount()

You can make calls to a remote endpoint like an Web Service or API to load data and is the best place to do so. Using setSate here will cause state updates and cause another rendering that happens before the browser updates the UI.
States should usually be assigned in the constructor though as mentioned above.

componentDidUpdate()

This method is called in response to props or state changes. setState should only be used with caution as may lead to inifinite loop. You can wrap it in a condition as shown below:

componentDidUpdate(prevProps) {
 //Compare the props
 if (this.props.title !== prevProps.title) {
   //do something -- here we have compared the current props with the previous props before doing something.
 }
}

componentWillUnmount()

This is the end of the lifecycle before the component is unmounted and destroyed. This can be used for any cleanups like clearing storage caches.

Create a basic ReactJS App, to follow through the example. You can check this post to get started.

In the example below to check out how these Component methods are called to depict the life cycle, the output for all these methods are logged to the Console.

The constructor initializes the state of the Component. The render method is called after every ComponentWill methods. Once the Component is rendered to the DOM, the ComponentDid method is called.

The componentDidMount() method runs after the component output has been rendered to the DOM.

import React, { Component } from "react";

class TestComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      increment: this.props.increment
    };
    console.log(this.state.increment, "Initialized");
  }

  componentWillMount() {
    this.setState({
      increment: this.state.increment = parseInt(this.state.increment) + 1
    });
    console.log(this.state.increment, "Inside ComponentWillMount");
  }

  componentDidMount() {
    this.setState({
      increment: this.state.increment = parseInt(this.state.increment) + 1
    });
    console.log(this.state.increment, "Inside ComponentDidMount");
  }

  componentWillUnmount() {
    this.setState({
      increment: this.state.increment = parseInt(this.state.increment) + 1
    });
    console.log(this.state.increment, "Inside ComponentWillUnmount");
  }

  componentWillUpdate() {
    console.log(this.state.increment, "Inside ComponentWillUpdate");
  }

  componentDidUpdate() {
    console.log(this.state.increment, "Inside ComponentDidUpdate");
  }
  

  render() {
    console.log(this.state.increment, "Render method called");
    return (
      <React.Fragment>
        <div>{this.state.increment} Render method called!</div>
      </React.Fragment>
    );
  }
}

export default TestComponent;
Order of how the Methods were called
DOM output

Whenever the TestComponent component is removed from the DOM, React calls the componentWillUnmount() lifecycle method.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.