Open In App

ReactJS componentWillUnmount() Method

Last Updated : 14 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In React, lifecycle methods allow you to manage the behaviour of components at different stages of their existence. One important lifecycle method for cleaning up resources and side effects is componentWillUnmount(). This method is called just before a component is removed from the DOM, making it an essential tool for avoiding memory leaks and ensuring proper resource management.

What is componentWillUnmount()?

The componentWillUnmount() method is part of React’s Class Component Lifecycle. It is invoked just before a component is unmounted and destroyed. This method is the perfect place to perform any necessary cleanup, such as:

  • Cancelling network requests
  • Clearing timers (like setInterval() or setTimeout())
  • Removing event listeners
  • Cleaning up subscriptions (such as WebSocket connections)

Syntax

componentWillUnmount() {
    // Cleanup code goes here
}
  • This method does not receive any arguments.
  • It is called automatically by React before the component is removed from the DOM.

When is componentWillUnmount() Called?

componentWillUnmount() is called when:

  • The component is about to be removed from the DOM.
  • This typically happens when a component is no longer needed, such as when it is conditionally rendered and the condition changes, or when navigating away from a page.

It’s important to note that componentWillUnmount() is only called for class components. In modern React applications, functional components are more commonly used, and useEffect() with a cleanup function replaces the need for componentWillUnmount().

Implimenting the componentWillUnmount() Method

1. Mouse Tracking with Cleanup using componentWillUnmount()

In this example, we will use the componentDidMount() and componentWillUnmount() methods for mouse tracking with cleanup.

JavaScript
import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = {
         showUser: true,
      };
   }

   render() {
      return (
         <div>
            <h1>Mouse Tracking</h1>
            <button onClick={() => this.setState({ showUser: false })}>
               Hide User
            </button>
            {this.state.showUser ? <User /> : null}
         </div>
      );
   }
}

class User extends React.Component {
   constructor() {
      super();
      this.state = {
         mousePosition: { x: 0, y: 0 },
      };
   }

   componentDidMount() {
      window.addEventListener('mousemove', this.trackMouse);
   }

   componentWillUnmount() {
      window.removeEventListener('mousemove', this.trackMouse);
      alert('User component removed and mouse tracking stopped!');
   }

   trackMouse = (event) => {
      this.setState({
         mousePosition: { x: event.clientX, y: event.clientY },
      });
   };

   render() {
      return (
         <div>
            <h3>User: Rahul</h3>
            <h4>Mouse Position</h4>
            <p>X: {this.state.mousePosition.x}, Y: {this.state.mousePosition.y}</p>
         </div>
      );
   }
}

export default App;

Output:

In this example

  • The App component controls whether the User component is visible using the showUser state.
  • Clicking the “Hide User” button sets showUser to false, hiding the User component.
  • When it mounts, it starts listening for mouse moves and updates the X and Y coordinates in the state.
  • When the User component is removed (because showUser is set to false), the componentWillUnmount() method cleans up by stopping the mouse tracking and removing the event listener.
  • While the User component is visible, it displays the current mouse position (X and Y coordinates) as the mouse moves.

2. Component Cleanup with componentWillUnmount()

We will cleanup the component with the help of the componentWillUnmount() method.

JavaScript
import React, { Component } from "react";

class MyComponent extends Component {
    componentWillUnmount() {
        console.log("Component is about to be removed from the DOM.");
    }

    render() {
        return <h1>Hello, I am a Component!</h1>;
    }
}

class App extends Component {
    state = { show: true };

    toggleComponent = () => {
        this.setState({ show: !this.state.show });
    };

    render() {
        return (
            <div>
                <button onClick={this.toggleComponent}>
                    {this.state.show ? "Unmount Component" : "Mount Component"}
                </button>
                {this.state.show && <MyComponent />}
            </div>
        );
    }
}

export default App;

Output
Animationkk

In this example

  • Initially, the “Hello, I am a Component!” message is displayed.
  • Click the “Unmount Component” button.
  • MyComponent disappears, and the console logs:
Component is about to be removed from the DOM.
  • Click the “Mount Component” button again.
  • MyComponent reappears.
  • You can toggle the component on and off to see componentWillUnmount() in action.

When to Use componentWillUnmount()?

Remove Event Listeners

If you added an event listener using window.addEventListener or document.addEventListener, clean it up here.

componentWillUnmount() {  
    window.removeEventListener('resize', this.handleResize);
}

Clear Timers or Intervals

If you use setInterval or setTimeout, clear them to prevent unnecessary executions.

componentWillUnmount() {  
    clearInterval(this.timer);
}

Canceling network requests

If your component is making API calls or network requests, and the component unmounts before the request completes, you should cancel the request to prevent it from affecting the component after it’s unmounted

componentWillUnmount() {  
    this.controller.abort();  // Cancel fetch request
}

Stopping Animations

If the component is running animations or transitions, use componentWillUnmount() to stop them when the component is unmounted, preventing animations from running unnecessarily.

componentWillUnmount() {  
    this.animation.stop();
}

Unsubscribe from External Services

For instance, when using libraries like Redux, Firebase, or WebSocket connections.

componentWillUnmount() {  
    this.unsubscribe();
}

Best Practices for Using componentWillUnmount()

  • Remove unnecessary resources (like event listeners and timers) when the component is being removed.
  • Avoid calling setState() in componentWillUnmount(), since the component is being unmounted.
  • Cancel ongoing requests and clean up any subscriptions.
  • Keep the method focused on cleanup to avoid unwanted actions after the component is gone

When Not to Use componentWillUnmount()?

There are certain scenarios where using componentWillUnmount() might be unnecessary

  • Simple Stateless Components: If your component doesn’t manage resources like timers or event listeners, you don’t need to implement componentWillUnmount().
  • Non-Interactive Components: Static components that simply display data or content generally do not need cleanup logic.

ReactJS componentWillUnmount() Method – FAQs

What is the componentWillUnmount() method used for?

componentWillUnmount() is a lifecycle method in React that is called right before a component is removed from the DOM. It is commonly used to clean up resources, such as removing event listeners, canceling API calls, clearing timers, or unsubscribing from subscriptions.

When is componentWillUnmount() called?

componentWillUnmount() is called just before the component is unmounted from the DOM.

Can I call setState() in componentWillUnmount()?

No, you should not call setState() inside componentWillUnmount(). Since the component is about to be unmounted, state updates would have no effect, and trying to update the state during unmounting can cause unnecessary issues.

What are common use cases for componentWillUnmount()?

Cleaning up subscriptions: If your component subscribes to an event or a store, you should unsubscribe in componentWillUnmount() to avoid memory leaks.

How is componentWillUnmount() different from componentDidUpdate()?

componentDidUpdate() is called after a component has been updated (i.e., after the render method), and it is used to handle actions based on state or prop changes.



Next Article

Similar Reads

three90RightbarBannerImg
  翻译: