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.

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.

Advertisements

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 )

Google photo

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

Twitter picture

You are commenting using your Twitter 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.