React Lifecycle Methods

In this tutorial, you will learn React lifecycle methods of a component step by step with some examples. It is the most important topic of React Js. So, You should read the given points without skipping any single step.

What’s Before –

Create React App Project

React Components

React Event Handling

Lifecycle of Component in React js

  • Lifecycle methods are  pre-defined functions in react js that are defined for components
  • lifecycle methods run at three different component phases like Mounting, Updating, & Unmounting

You can see the following lifecycle methods diagram In which you can see which lifecycle methods are used at which phases.

react lifecycle methods

Important Points –

  • You can also override  lifecycle methods with your custom code to run at a particular phase & time interval
  • It is not necessary that to use lifecycle methods in your component. These are optional methods that totally depend on the requirement of your project functionality
  • When you create a component and execute it then, first of all, It goes through at the Mounting phase, after that updating phase & at last unmounting phase

Now, We need to know all the lifecycle methods phase by phase from the next step. After that, you will completely understand its concept.

Mounting Phase

Mounting is the first component phase at which, a component creates new elements and inserted them into the DOM tree

Mounting phase has the following lifecycle methods that must be defined within a class component in the given order.

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

Now let’s understand these methods one by one from the next step –

1. constructor()

The constructor() method is defined within the class component and It is called before the component is mounted.

Even The constructor() method is defined with a single parameter props.

an in-build methods super(props) must be called first  before writing any code statement within the constructor() 

You should defiend constructor() method only if you need to initialize state and bind methods

Example – 

When you initialize a state –

class Developer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {fullName: "Md Nurullah"};
  }
  render() {
    return (
      <p>My Name is {this.state.fullName}</p>
    );
  }
}

When you bind a method –

class Developer extends React.Component {
 constructor(props){
 super(props);
 this.intro = this.intro.bind(this);
 }
 function intro(){
  document.write("My Name is Md Nurullah");
 }
 return <button onClick={this.intro}>Click me</button
}

2. getDerivedStateFromProps()

The getDerivedStateFromProps() method is defined within the class component and It is called before the calling render() method & mounting a component and after calling constructor() method.

You must define getDerivedStateFromProps() with two parameters state & props and return the changed state in object format or null value.

class Developer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {fullName: "Md Nurullah"};
  }
  static getDerivedStateFromProps(props, state) {
    return {fullName: props.name };
  }
  render() {
    return (
      <p>My Name is {this.state.fullName}</hp>
    );
  }
}

Here I have passed a props as name=”Noor Khan” to the Developer component

<Developer name="Noor Khan" />

After running this code, you will get the result, Noor Khan, because getDerivedStateFromProps() method executes after executing the constructor method. So, the value of fullName: Md Nurullah is updated with value of fullName: props.name.

3. render()

The render() method is defined within the class component and It is called before mounting a component and after calling constructor() method and getDerivedStateFromProps().

The render() method can be return the following thing to the DOM –

  • React elements
  • Array and Fragments
  • Portals
  • String & numbers
  • Booleans or Null

Example – 

class Student extends React.Component {
  constructor(props) {
    super(props);
    this.state = {studentName: "Md Nurullah"};
  }
  static getDerivedStateFromProps(props, state) {
    return {studentName: props.name };
  }
  render() {
    return (
      <hp>My Name is {this.state.studentName}</hp>
    );
  }
}

Here I have passed a props as name=”Noor Khan” to the Student component

<Student name="Noor Khan" />

4. componentDidMount()

The componentDidMount() method is defined within the class component and It is called after calling constructor() method, getDerivedStateFromProps(), & render() method and Even after the component was mounted.

The componentDidMount() is called once in a component lifecycle and after the first rendering.

You can use acomponentDidMount()  for integrating with other javascript frameworks and any function with setTimeout & setInterval. Also for ajax request and API calling.

Example –

class Developer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {fullName: "Md Nurullah"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({fullName: "Noor Khan"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Name is {this.state.fullName}</h1>
    );
  }
}

Updating Phase

Updating is the second phase of a component that comes after completing the mounting phase. So, At this phase, A component will be updated, if there are changes in its props/state.

Updating phase has the following lifecycle methods that must be defined within a class component in the given order and It will be called when the component is updated

  • getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

1. getDerivedStateFromProps()

getDerivedStateFromProps() is called at both mounting & updating phase before calling render methods.

You have already learned this method in the mounting phase. Here, you need not repeat it again

Here You will learn how to use this method function to update data on button click.

Example –

In this example, we will update the full name “Rapsan Jani” with another full name “Noor Khan” by clicking a button and we will see how to use getDerivedStateFromProps() in the updating phase.

So let’s start its coding –

File Name – Developer.js

In this code, I have created a class component with the name Developer to render the value of state and It is called within another render() method of the App.js file.

In this code props.name is defined that will be passed from the App.js file.

import React from "react"

class Developer extends React.Component {
    constructor(props) {
      super(props);
      this.state = {fullName:props.name};
    }
   static getDerivedStateFromProps(props, state) {
        if(props.name!=state.fullName){
            return {fullName: props.name };
        }
        return null; 
      
     } 
 
    render() {
      return <h1>My Name is {this.state.fullName}</h1>
    }
  }
  export default Developer;

File Name – App.js

From this code, first of all, the full name “Rapsan Jani” is declared with state that is passed as props to the Developer component

When you click the button value of the state will be updated using this.setState({name:”Noor Khan”}). 

But As you know that state will never update without using this.setState(). So, In Developer component, we need to define this.setState() but here I  have defined getDerivedStateFromProps() function instead of this.setState(). So that we can apply if-else condition to update data

import React from "react"
import Developer from "./Developer";

class App extends React.Component {
 
  constructor(props) {
    super(props);
    this.state = {name:"Rapsan Jani"};
  }
  updateName =()=>{
    this.setState({name:"Noor Khan"});
  }
  render(){
    return (
      <React.Fragment>
          <Developer name={this.state.name} />
          <button onClick={this.updateName}>update</button>
      </React.Fragment>
  );
  }

}
export default App;

2. shouldComponentUpdate()

ShouldComponentUpdate() method is defined with two parameters nextProps & nextState before render() method within the class component and It will be executed before rendering data if any changes are updated in state & props.

Where –

  • nextProps will receive changes value of props
  • nextState will receive changes value of state

By default, It returns true. If you return it false then component will not re-render on updating the existing value of state & props

Example –

We will see its example by using shouldComponentUpdate() method in the example of getDerivedStateFromProps() 

Here, We will stop rendering the Developer component using shouldComponentUpdate() if both values ( default state value and changes value on the click button ) are the same

import React from "react"

class Developer extends React.Component {
    constructor(props) {
      super(props);
      this.state = {fullName:props.name};
    }
   static getDerivedStateFromProps(props, state) {
        if(props.name!=state.fullName){
            return {fullName: props.name };
        }
        return null; 
      
     } 
    shouldComponentUpdate(nextProps, nextState) {
        if(props.name!=state.fullName){
            return false
        }
     } 
    render() {
      return <h1>My Name is {this.state.fullName}</h1>
    }
  }
  export default Developer;

3. render()

We have already learned the render() method in Mounting Phase. So, Here we need not repeat it again. But You should keep one thing in your mind that the render() method is executed in both phases Mounting & Updating.

Means that, If you create new element or update existing values of state & props, render() method will be defnately executed to render those data to the HTML page

4. getSnapshotBeforeUpdate()

The getSnapshotBeforeUpdate() method is defined after the shouldComponentUpdate() and before the render() method and It is executed before the real DOM is updated.

Returned value of this method is passed to the componentDidUpdate() as a third parameter. So, componentDidUpdate() must be defined with this method.

If you need to store & see the old values of state/props before updating  virual DOM, Then you can use this method.

Syntax –

getSnapshotBeforeUpdate(prevProps, prevState){
}

Where –

  • prevProps – will receive old value of props
  • prevState – will receive old value of state

Now, let’s understand the concept of componentDidUpdate() method. after that we will see an example by using these both method together.

5. componentDidUpdate()

The componentDidMount() method is defined after the shouldComponentUpdate() and before the render() method and It executes after the real DOM is updated.

This method will not execute if shouldComponentUpdate() methods returns false.

Syntax –

componentDidUpdate(prevProps, PrevState, snapshot){
}

Where –

  • prevProps  will receive old value of props
  • prevState will receive old value of state
  • snapshot will receive the returned value from the getSnapshotBeforeUpdate() method

Example –

File Name – Developer.js

import React from "react"
class Developer extends React.Component {
    constructor(props) {
      super(props);
      this.state = {fullName:props.name};
    }
   static getDerivedStateFromProps(props, state) {
        if(props.name!=state.fullName){
            return {fullName: props.name };
        }
        return null; 
      
     } 
    shouldComponentUpdate(nextProps, nextState) {
        if(props.name!=state.fullName){
            return true
        }
     } 
  getSnapshotBeforeUpdate(prevProps, prevState){
   console.log(prevProps, prevState)
    return "Welcome to Codingstatus";
   }
  componentDidUpdate(prevProps, prevState, snapshot){
   console.log(prevProps, prevState, snapshot)
 }
    render() {
      return <h1>My Name is {this.state.fullName}</h1>
    }
  }
  export default Developer;

Unmounting Phase

Updating is the third phase of a component that comes after completing the mounting & updating phase. At this phase, a component is completely removed from the DOM.

Updating phase has only one lifecycle method –

  • componentWillUnmount()

1. componentWillUnmount()

componentWillUnmount() will execute when a component is about to distryed/ removed from the DOM

In this method, You can perform many functionalities like canceling network request, removed subscriptions, & invalidating timers

Example –

File Name – App.js

import React from "react"
import Developer from "./Developer";
class App extends React.Component {

componentWillUnmount(){
console.log("App component was unmounted")
} render(){ return <h3>Welcome to CodingStatus</h3> } } export default App;

File Name – index.js

import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App /> , document.getElementById('root'));
ReactDOM.unmountComponentAtNode(document.getElementById('root'));