Implementing componentWillUnmount in React Hooks

Last updated : Jul 30, 2023 12:00 AM

React Js unmounts components that are not in use. When React unmounts components, it executes componentWillUnmount() in each component if they have one.

Below is how to implement componentWillUnmount() in a class component.

import { Component } from "react";
import { Link } from "react-router-dom";

export default class App extends Component{
  
   componentWillUnmount() {
      console.log("Unmounting App")
   }
   render(){
      return <Link to="/toFunctionalComponent">To Functional Component</Link>
   }
}

I can navigate another page by clicking on the "To Functional Component" link. By doing that, I steer away from the App component. Hence React Js executes componentWillUnmount() in the App component immediately before it unmounts.

componentWillUnmount() equivalent in React Js hooks

Now I land on the FunctionalComponent page. Here is how to implement componentWillUnmount() in React Js hooks.

import { useEffect } from "react"
import { Link } from "react-router-dom"

export const FunctionalComponent = () =>{

   useEffect(() => {
      return(() => {
         console.log("Unmounting FunctionalComponent")
      })
   },[])

 return(
   <Link to="/">To Home</Link>
 )
}

I use a regular useEffect() hook with an empty dependency array. Then I use a return statement and pass a function to the return statement as the argument. React Js executes the contents of that return statement when the component unmounts. Therefore, clicking the "To Home" link will unmount the FunctionalComponent, which would result in executing the console.log("Unmounting FunctionalComponent").

What is the purpose of componentWillUnmount()?

My components may start services like timers, subscribe to services, or make network requests upon mounting. Those services are not necessary after the component unmounts. Leaving them as they are may cause slowness and poor performance in the application. Therefore, I can use the componentWillUnmount() lifecycle method or the hook equivalent to free those services when the component unmounts.

Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...