React Lifecycles

React lifecycle methods are given to class components when the mounting, update and unmount during these three phases.

Mounting is the process when a component is rendered on the page.

Unmounting is the process when a component is removed from the page.

Some of the most important lifecycle methods are:

componentDidMount()

This method is called when a component is rendered on the page. This function is called even before the first rendering on the page.

App.js:

import React, { Component } from 'react'

class App extends Component {
   componentDidMount() {
      alert('I am a mounted component')
   }

   render() {
      return (
         <div>
            <></>
         </div>
      )
   }
}

export default App

componentDidUpdate()

This lifecycle method is called when there is an update in the DOM. For example,

import React, { Component } from 'react'

class App extends Component {
   state  = {
      count: 0
   }
   update = () =>  {
      this.setState({count: this.state.count + 1})
   }
   componentDidMount() {
      alert('I am a mounted component')
   }
   componentDidUpdate() {
      alert('I am an updated component')
   }
   render() {
      return (
         <div>
            <button onClick={this.update}>Update state</button>
         </div>
      )
   }
}

The state variable on click of the button is updated and therefore triggers the componentDidUpdate() lifecycle.

Result:

componentWillUnmount()

This function is called when a component is being removed from a page. This method is mostly used in clearing functions that were called during mounting, such as setInterval(), event listeners, and so on.

useEffect Hook

All the lifecycle methods mentioned above are available only for class components. React also provided a special Hook for functional components called useEffect that combines the componentDidMount(), componentDidUpdate() and componentWillUnmount(). Let’s take a look at an example:

import React, { useEffect, useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    alert("Number of button clicks: " + count);
  });
  function increase() {
    setCount(count + 1);
  }
  return (
    <div>
      <p>{count}</p>
      <button onClick={increase}> Increase </button>
    </div>
  );
}

useEffect runs after the first render and after every update. To call the method only when a particular thing changes, useEffect takes the variable as a second argument:

import React, { useEffect, useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    alert("Number of button clicks: " + count);
  }, [count]);
  function increase() {
    setCount(count + 1);
  }
  return (
    <div>
      <p>{count}</p>
      <button onClick={increase}> Increase </button>
    </div>
  );
}

componentWillMount() :

This is triggered before the component is rendered, works in both server and client- rendering. This Lifecycle method is deprecated and will be removed in a later versions of React.

componentWillReceiveProps():

This is triggered if the props of that particular component is updated before re-rendering that component after an update. This Lifecycle method is also deprecated.

shouldComponentUpdate():

returns a true or false value depending on whether the component should be updated or not. This is true by default

Other lifecycle events are:

  • getDerivedStateFromProps():
  • componentWillUpdate() : called before the component is rendered.
  • getSnapshotBeforeUpdate(): Runs before React applies the result of render to the document, and returns an object to be given to componentDidUpdate. Useful for saving things such as scroll position before rendering causes changes to it.

Note: the presence of getSnapshotBeforeUpdate prevents any of the deprecated lifecycle events from running.

Each of these lifecycle events can be configured to monitor and manipulate a component during mounting, updating, and unmounting.

Applications

 The below example shows the use of some of the lifecycle methods, some of them might give errors because they are now deprecated.

import React, { Component } from 'react'

class App extends Component {
   state  = {
      count: 0
   }
   update = () =>  {
      this.setState({count: this.state.count + 1})
   }
   componentWillMount() {
      console.log('Mounting...')
   }
   componentDidMount() {
      alert('I am a mounted component')
   }
   componentDidUpdate() {
      alert('I am an updated component')
   }
   shouldComponentUpdate(newProps, newState){
      return true
   }
   getSnapshotBeforeUpdate(){
      console.log('snapshot taken')
   }
   render() {
      return (
         <div>
            <button onClick={this.update}>Update state</button>
         </div>
      )
   }
}

export default App