Implementing componentWillUnmount in React Hooks

Last updated : October 23, 2022

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")
    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")

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

L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.

Comments are disabled

No Comments