×

React Component Life-Cycle

React Component Life-Cycle

In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as follows:

  • Initial Phase
  • Mounting Phase
  • Updating Phase
  • Unmounting Phase

There are some methods in every phase of the lifecycle. Let us elaborate on these phases one by one:

Initial Phase

 It is termed as the birth phase of the lifecycle of a ReactJS component.  In this phase, the component includes the initial state and default props. These default properties happen in the component’s constructor. This phase occurs only once and includes the following methods:

  • getDefaultProps()

 It is used for specifying the default value of this.props. It invokes before the creation of the component.

  • getInitialState()

It is used for specifying the default value of this.state.

Mounting Phase

In this phase, there is the creation of a component's instance and inserted it into the DOM. It includes the following methods:

  • componentWillMount()

It invokes immediately before the rendering of a component into the DOM. If there is a case that you are calling setState() inside this method, the component will not be re-render.

  • componentDidMount()

It invoked immediately after the rendering of a component and placed on the DOM. Now, you can perform any DOM querying operations.

  • render()

It is defined in every component. It is responsible for returning the single root HTML node element. If you don’t want to render anything, you can create a null or false value.

Updating Phase

It is the next phase of the React component lifecycle. Here, we get new Props and change State. This phase also allows you to handle the interaction with the user and provide communication with the hierarchy of components. The main aim of this phase is ensuring that the component is displaying its latest version.

As a difference from the Birth or Death phase, this phase repeats again and again. It includes the following methods:

  • componentWillReceiveProps()

 It invokes when a component receives new props. If you require the updation of the state in response to prop changes, you have to compare this.props and nextProps for performing the state transition by using this.setState() method.

  • shouldComponentUpdate()

It invokes whenever a component decided to change/update to the DOM. It allows you to control the behavior of the component and to update itself. The component will update when this method returns true. Otherwise, the component will skip updating.

  • componentWillUpdate()

It invokes just before the occurring of component updation. Here, you cannot change the state of the component by invoking this.setState() method. It will not be called if the method shouldComponentUpdate() returns false.

  • render()

It invokes for the examining of this.props and this.state and returns the types like React Elements, Arrays, and Fragments, Booleans or null, String, and Number. If the method shouldComponentUpdate() returns false, the code inside render() will be invoked again to ensure that the component displays itself properly.

  • componentDidUpdate()

It invokes immediately after the occurring of the component's updating. In this method, you can put any code inside it which you want to execute once the occurring of updating. This method does not invoke the initial render.

Unmounting Phase

It is the final phase of the React component lifecycle. This method is called whenever the instance of the component is destroyed and unmounted from the DOM. This phase includes only one method which is given below:

  • componentWillUnmount()

This method immediately invokes before a component is permanently destroyed and unmounted. It performs any necessary cleanup related tasks such as invalidating timers, event listener, canceling network requests, or cleaning up the elements of DOM. If the instance of the component is unmounted, it will not be possible to mount it again.

Example:

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { world: "World" };
    this.changeState = this.changeState.bind(this);
  }

  render() {
    return (
      <div>
        <h2>Example of ReactJS Components Lifecycle</h2>
        <p>Hello {this.state.world}</p>
        <button onClick={this.changeState}>Click Here!</button>
      </div>
    );
  }

  componentWillMount() {
    console.log('ComponentWillMOUNT!');
  }

  componentDidMount() {
    console.log('ComponentDidMOUNT!');
  }

  changeState() {
    this.setState({
      world: "All!! - It's an example of ReactJS component lifecycle."
    });
  }

  componentWillReceiveProps(newProps) {
    console.log('ComponentWillReceiveProps!');
  }

  shouldComponentUpdate(newProps, newState) {
    return true;
  }

  componentWillUpdate(nextProps, nextState) {
    console.log('ComponentWillUPDATE!');
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('ComponentDidUPDATE!');
  }

  componentWillUnmount() {
    console.log('ComponentWillUNMOUNT!');
  }
}

export default App;

Output:

Example of Reactjs Lifecycle

When you will click on the button, you will get the following output:

When you will click on the button

Related Topics

React Constructors

What is constructor? The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in...

4 minutes read.

React Error Boundaries

React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

3 minutes read.

React Redux

How to Use Redux with React Hooks It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface....

5 minutes read.

React Bootstrap

React Bootstrap React has a widely used JavaScript framework for creating web applications, and Bootstrap has become the most popular CSS framework. Single-page apps have become popular from the last few...

9 minutes read.

React Events

React Events An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the...

2 minutes read.

Difference Between React Flux and MVC

React Flux vs MVC MVC MVC is an acronym of 'Model View Controller.' It is the architectural pattern that is used to develop the user interface. It has three different logical components: The...

2 minutes read.

ReactJS vs AngularJS

Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

5 minutes read.

Comparison between React and Vue

Comparison between React and Vue React, and Vue both are the two most famous libraries of JavaScript that are used for creating thousands of websites today. The React and Vue both...

3 minutes read.

React Forms

React Forms Forms are the important part of any web application. It allows the interaction of the user with the app as well as the gathering of the information from the...

3 minutes read.

React Props Validation

React Props Validation As we know, props are a suitable mechanism for passing the read-only attributes to react components. The props are required to be correctly used in the component. If it is...

5 minutes read.

React Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

3 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

React Lists

React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

2 minutes read.

React State

React State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over time. The change...

3 minutes read.

How to use React Context

React Context React Context is used to pass the data through the component tree without passing the props down manually at the every level. In React Application, the data is passed in a top-down approach...

4 minutes read.

React Table

React Table The table represents an arrangement that organizes the information in the form of rows and columns. The table is mainly used for storing and displaying the data within a structured format. Features of...

2 minutes read.

ReactJS Versions

ReactJS Versions The Complete set of release history of ReactJS is elaborated as follows. The complete set of full documentation of recent releases is on GitHub. S.noVersionRelease DateExplanation1.0.3.029/05/2013Initially released for public.2.0.4.029/07/2013Supporting comments...

4 minutes read.

React Conditional Rendering

React Conditional Rendering In React, the working of the conditional rendering is similar to the condition works in JavaScript. We use JavaScript operators for creating elements that represent the current state, and then the React...

3 minutes read.

React Router

What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

10 minutes read.

React Refs

React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

7 minutes read.