ReactJS componentWillUnmount() Method
Last Updated :
14 Feb, 2025
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

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.
Similar Reads
ReactJS componentWillUnmount() Method
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
5 min read
ReactJS componentDidMount() Method
In React, lifecycle methods allow you to manage the behaviour of components at different stages of their existence. One important lifecycle method for initializing data or setting up resources after a component is mounted is componentDidMount(). This method is called immediately after the component
6 min read
ReactJS UNSAFE_componentWillMount() Method
The componentWillMount() method invokes right before our React component gets loaded or mounted in the DOM (Document Object Model). It is called during the mounting phase of the React Life-cycle, i.e., before render(). It is used to fetch data from outside the component by executing the React code s
3 min read
What is ComponentWillMount() method in ReactJS ?
ReactJS requires several components to represent a unit of logic for specific functionality. The componentWillMount lifecycle method is an ideal choice when it comes to updating business logic, app configuration updates, and API calls. PrerequisitesReact JSReact JS class componentsComponentWillMount
4 min read
ReactJS UNSAFE_componentWillUpdate() Method
The componentWillUpdate() method provides us the control to manipulate our React component just before it receives new props or state values. It is called just before the rendering of our component during the updating phase of the React Life-cycle ,i.e., this method gets triggered after the updation
3 min read
ReactJS componentDidUpdate() Method
In React, lifecycle methods allow you to manage the behaviour of components at different stages of their existence. One important lifecycle method for handling actions after updates have occurred is componentDidUpdate(). This method is called immediately after a componentâs updates are applied to th
5 min read
ReactJS componentDidCatch() Method
The componentDidCatch() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the commit phase, so unlike getDerivedStateFromError() w
2 min read
ReactJS isDOMComponent() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use isDOMComponent() method. This
2 min read
When is the componentWillUnmount method called?
The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e. before the component gets unmounted. Prerequisites:NPM & NodeR
2 min read
How to use componentWillMount() in React Hooks?
The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle. You cannot use any of the existing React lifecycle methods like Com
2 min read