ReactJS componentWillUnmount() Method
Last Updated :
07 Oct, 2024
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.
In this article, we will dive deep into the componentWillUnmount() method, exploring what it does, when to use it, and how it fits into the component lifecycle.
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:
- Canceling network requests
- Clearing timers (like setInterval() or setTimeout())
- Removing event listeners
- Cleaning up subscriptions (such as WebSocket connections)
Syntax:
componentWillUnmount() {
// Cleanup code goes here
}
Why Use componentWillUnmount()?
The primary use case of componentWillUnmount() is cleanup. In React, failing to clean up side effects like timers, network requests, or subscriptions can lead to memory leaks and unexpected behaviours in your application.
Common Cleanup Tasks:
- Timers: Clear any active timers (setTimeout(), setInterval(), etc.) to avoid them running after the component is removed.
- Event Listeners: Remove any event listeners (e.g., window.addEventListener() or custom event listeners) to prevent memory leaks.
- Network Requests: Cancel any ongoing network requests or subscriptions to prevent updates to unmounted components.
- External Libraries: Cleanup or dispose of any external resources (like WebSocket connections, file system operations, etc.) to ensure the application doesn’t hold onto unnecessary resources.
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().
Steps To Use componentWillUnmount() Method
Create a React application using the following command
npx create-react-app functiondemo
cd functiondemo
Project Structure
Project Structure
Example: In this example, we are going to build a name color application that changes the color of the text when the component is rendered in the DOM tree.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
JavaScript
//App.js
import React from 'react';
class ComponentOne extends React.Component {
// Defining the componentWillUnmount method
componentWillUnmount() {
alert('The component is going to be unmounted');
}
render() {
return <h1>Hello Geeks!</h1>;
}
}
class App extends React.Component {
state = { display: true };
delete = () => {
this.setState({ display: false });
};
render() {
let comp;
if (this.state.display) {
comp = <ComponentOne />;
}
return (
<div>
{comp}
<button onClick={this.delete}>
Delete the component
</button>
</div>
);
}
}
export default App;
Note: You can define your own styling in the App.css file.
Run the application using the following command.
npm start
Output
ReactJS componentWillUnmount() Method
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.