componentWillUnmount() is a React lifecycle method invoked just before a component is removed from the DOM. It is primarily used to clean up resources and prevent memory leaks.
- Remove event listeners or subscriptions to avoid unwanted updates.
- Clear timers or intervals set during the component’s lifecycle.
- Cancel ongoing network requests or asynchronous operations.
- Perform any necessary cleanup to maintain optimal performance.
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.
componentWillUnmount() Execution Timing
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().
Implementing the componentWillUnmount() Method
It Use this method to clean up subscriptions, timers, or any side effects before the component is removed from the DOM, ensuring efficient resource management.
1. Mouse Tracking with Cleanup using componentWillUnmount()
We will use the componentDidMount() and componentWillUnmount() methods for mouse tracking with cleanup.
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:
- The App component controls the rendering of the User component using the showUser state.
- When showUser becomes false, the User component unmounts.
- On mount, it adds a mousemove listener to track cursor coordinates.
- On unmount, componentWillUnmount() removes the listener to prevent memory leaks.
- While mounted, it displays the updated mouse position.
2. Component Cleanup with componentWillUnmount()
We will cleanup the component with the help of the componentWillUnmount() method.
import React, { Component } from "react";
class MyComponent extends Component {