×

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 Component API

React Component API It is a top-level API. It provides reusability to the code in the application and makes it completely individual. It has several methods for: Creating Elements.Transforming Elements.Fragments. Now, we are explaining the three...

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.

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.

React Native vs ReactJS

Difference between React Native and ReactJS React Native React Native is also an open-source JavaScript framework that is used for the development of a mobile application for iOS Android and Windows. It...

6 minutes read.

React CSS

What is React CSS React CSS is used to provide the style to the React applications. The style attribute adds dynamically-computed styles at render time, and it is one of the most used...

5 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 Map

React Map The map() is the standard function of JavaScript, which can be called at any array. The map() method is used for traversing and displaying a list of the similar objects of...

2 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 Components

React Components Former, the developers used to write more than thousands of lines of code to develop a single-page application. These applications follow the structure of traditional DOM, and it was very challenging to make...

2 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 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.

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 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.

React Fragments

React Fragments The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM. In React,...

2 minutes read.

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

5 minutes read.

React Portals

React Portals React portals were introduced by React 16.0 in September 2017. It gives you a way to render the element outside of the component hierarchy, i.e., within a separate component. Before React 16.0, it...

3 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.

React JSX

React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

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 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.