Replacing Lifecycle methods with React Hooks

What are React lifecycle methods?

React lifecycle methods are the events or scenarios that happen while your component is rendered for the first time (birth) and discarded after its use (death). By default, this method can’t be used in functional components directly.

Note: React 16.8.0 is the first release to support Hooks.

  • Lifecycle events in React play a crucial role while writing React components.
  • We as Developers often need lifecycle events to handle various effects such as fetching data on the mount, cleaning up before the component unmounts, sanitizing props when the component updates, etc.

What before React 16.8.0 🤪

  • The most common solution for handling lifecycle events required ES6 class-based components which will see later in this article.

But now, 💪 💪

  • We can implement their functional components with React development with the help of React Hooks and Hooks enable functional components to implement them efficiently.
  • Hooks allow us to use state and other React features without writing a class component.

Here’s the entire lifecycle of a component:

Capture.PNG

In React, each component has stages during its lifecycle, generally referred to as React component’s lifecycle.

What is React component’s lifecycle???

See in React, components go through a lifecycle of events (Different phases in the lifecycle):

  1. Mounting ( When the component is initially rendered in DOM )
  2. Updating (When the component is being updated through states or props)
  3. Unmounting (When the component is removed from the DOM)

I can understand it sounds high Mounting, Updating, Unmounting 😃 😃 but You can think of these events as a component’s birth, growth, and death, respectively.

So Are you confused with States and Props??

States

A set of data that an individual component holds.

Props

Props are similar to the argument passed to a function. The component accepts props to render contents conditionally based on the props provided.

Or data that is being passed from one component to another.

Mounting lifecycle methods

It has four built-in methods that are called in this order

  • constructor()
  • static getDerivedStateFrom Props()
  • render()
  • componentDidMount()

let's Discuss all 😎

constructor()

  • Constructor is a method that is executed as soon your components start to render by React.
  • Constructor executes first than any other method inside your react component
const MyComponent extends React.Component {
  constructor(props) {
   super(props) 
    this.state = {
       name: "pankaj"
    }  
    this.handlePoints = this.handlePoints.bind(this) 
    }   
}

static getDerivedStateFrom Props()

  • getDerivedStateFrom Props() is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
  • Its main function is to ensure that the state and props are in sync for when it’s required.

render()

  • After the static getDerivedStateFrom Props() method is called, the next lifecycle method in line is the render method.

componentDidMount()

  • This method is usually called when the component has finished rendering for the first time.
  • This lifecycle method is called mostly for fetching some data or manipulating the DOM after the component is rendered.
  • componentDidMount() is best suited to make API calls and update the state.
Before (class-based component):

import React from "react";

class Component extends React.Component {
  componentDidMount() {
    //logic
  }

  render() {
    return <h1>Hello</h1>;
  }
};
After (functional component using Hooks):

import React, { useEffect } from "react";

const Component = () => {
  useEffect(() => {  //the useEffect Hook will be invoked when the component mounts.
//logic
  }, []);  // Pass an empty array to run only callback on mount only.

  return <h1>Hello World</h1>;
};

Updating Lifecycle Methods

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

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

static getDerivedStateFromProps()

  • This is an opportunity to change the state based on the value of props, which can be useful for initialization.

shouldComponentUpdate()

  • This is an opportunity to prevent rendering if you know that props and state have not changed.
  • The default implementation always returns true.
  • If you return false, the render will not occur (and children will not render either), and the remaining lifecycle methods will be skipped.
  • But since Hooks can be only used in functional component, and functional component internally handles the shouldComponentUpdate( ) method for use.
shouldComponentUpdate(nextProps, nextState)

getSnapshotBeforeUpdate()

  • This is called after render, but before the changes are committed to the DOM. If you need to do any calculations based on the old DOM this is the time to do it.
// Called after render() but before updating the DOM
// A good time to make calculations based on old DOM nodes.
// The value returned here is passed into componentDidUpdate
getSnapshotBeforeUpdate(nextProps, nextState) {
console.log('[getSnapshotBeforeUpdate]', 'About to update...');
return `Time is ${Date.now()}`;
}

componentDidUpdate()

  • Render is done. DOM changes have been committed. You can use this opportunity to operate on the DOM if you need to.
  • It is a lifecycle method that executes after an update in the component and checks if a specific prop or state has changed.
Before (class-based component):

import React from "react";

class Component extends React.Component {
  componentDidUpdate() {
    //logic
  }

  render() {
    return <h1>Hello</h1>;
  }
};
After (functional component using Hooks):

import React, { useEffect } from "react";

const Component = () => {
  useEffect(() => { 
//logic
  });  

  return <h1>Hello World</h1>;
};

This looks very similar to how we handled componentDidMount........

Isn’t it????

What is the difference??

  • The most important thing to note is the optional second argument ([]) is no longer present.
  • This means that the Hook will be evaluated on every re-render of the component.

Unmounting Lifecycle Methods

This method is called when a component is being removed from the DOM:

  • componentWillUnmount()

componentWillUnmount()

  • It is a lifecycle method that runs or executes when the component is about to be removed or unmounted from the DOM. It is called only once during the lifecycle of a component.
Before (class-based component):

import React from "react";

class Component extends React.Component {
  componentWillUnmount() {
    //logic
  }

  render() {
    return <h1>Hello</h1>;
  }
};
After (functional component using Hooks):

import React, { useEffect } from "react";

const Component = () => {
  useEffect(() => {
    return () => {
            console.log("return right before the component is removed from the DOM.");
        }
  }, []);

  return <h1>Hello World</h1>;
};

This again looks very similar to how we handled componentDidMount........

  • The only difference is the return statement inside of the useEffect function body. If a function is returned from useEffect, that function is invoked only when the component is removed from the DOM.