ReactJS - componentWillUnmount() Method



Components are the building blocks of our React app. They are similar to LEGO pieces that we assemble to make a larger building. componentWillUnmount() is one of the lifecycle methods available to each component.

The componentWillUnmount method is a part of the React class component. React calls it just before a component is removed or "unmounted" from the screen. This is a common location for cleaning up tasks such as canceling data fetching or deactivating subscriptions.

Syntax

componentWillUnmount() {
   // Cleanup and resource release logic here
}

Parameters

componentWillUnmount does not accept any parameters. It is a lifecycle function that React calls when the component is going to be unmounted.

Return Value

Nothing should be returned by the componentWillUnmount function. It is used to do cleanup operations and release resources rather than return a value.

Examples

Example

Let us make a basic example app to show how the componentWillUnmount function in a React class component can be used. In this example, we will create a counter app that starts a timer when the component is mounted and stops it when it's unmounted.

import React, { Component } from 'react';

class App extends Component {
   state = {
      count: 0,
   };
   timerID = null;   
   componentDidMount() {
      
      // Start the timer when the component mounts
      this.timerID = setInterval(() => {
         this.setState((prevState) => ({ count: prevState.count + 1 }));
      }, 1000);
   }   
   componentWillUnmount() {
      // Stop the timer when the component unmounts
      clearInterval(this.timerID);
   }   
   render() {
      return (
         <div>
            <h1>Counter: {this.state.count}</h1>
         </div>
      );
   }
}

export default App;

Output

counter_7

We have created a CounterApp component that extends Component. In the componentDidMount method, we started a timer with the help of setInterval to update the count state every second. This is a simple counter that increments every second. In the componentWillUnmount method, we stop the timer with the help of clearInterval to prevent memory leaks when the component is unmounted. The render method displays the current count value.

This app shows how to use the componentWillUnmount function to clear up resources. In our case it is to stop a timer, when a component is unmounted.

Example − User Profile App

In this app we will have a user profile display, and the componentWillUnmount() function is used for any cleanup that might be needed when the component is unmounted.

UserProfileApp.js

import React, { Component } from 'react';
import './App.css';

class UserProfileApp extends Component {
   state = {
      userProfile: {
         username: 'Akshay_Sharma',
         email: 'akshay@example.com',
      },
   };   
   componentDidMount() {
      
      // Fetch user profile data when the component mounts
   }   
   componentWillUnmount() {
      
      // Any cleanup needed for user profile app can be done here
      console.log('UserProfileApp will unmount');
   }   
   render() {
      const { username, email } = this.state.userProfile;
      return (
         <div className='App user-profile-container'>
            <h1>User Profile</h1>
            <p>Username: {username}</p>
            <p>Email: {email}</p>
         </div>
      );
   }
}

export default UserProfileApp;

App.css

.user-profile-container {
   max-width: 400px;
   margin: auto;
   padding: 20px;
   border: 1px solid #ccc;
   border-radius: 8px;
   box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
   background-color:rgb(224, 204, 178);
}
h1 {
   color: red;
}
p {
   margin: 8px 0;
   color: green;
}

Output

user profile name

Example − Countdown Timer App

In this app we will have a countdown timer that starts when the component mounts and stops when the component is about to unmount. So the code for this app is as follows −

CountdownTimerApp.js

import React, { Component } from 'react';
import './App.css'

class CountdownTimerApp extends Component {
   state = {
      time: 10,
   };
   timerID = null;   
   componentDidMount() {
      
      // Start the countdown timer when the component mounts
      this.timerID = setInterval(() => {
         this.setState((prevState) => ({ time: prevState.time - 1 }));
      }, 1000);
   }   
   componentWillUnmount() {
      
      // Stop the countdown timer when the component unmounts
      clearInterval(this.timerID);
   }   
   render() {
      return (
         <div className='App'>
            <h1>Countdown Timer: {this.state.time}s</h1>
         </div>
      );
   }
}

export default CountdownTimerApp;

Output

countdown timer

The componentWillUnmount() method is used to clear intervals or perform cleanup when the components are about to unmount.

Limitations

During development in React's Strict Mode, React can use componentDidMount, immediately call componentWillUnmount, and then call componentDidMount again. This is a useful tool for identifying issues with componentWillUnmount and ensuring that it properly copies componentDidMount.

Summary

componentWillUnmount is a method in React class components that is used to clean up resources before clearing a component from the screen. It is required for operations such as stopping data fetching and deactivating subscriptions. We ensure that our component runs smoothly throughout its lifecycle by duplicating the behavior from componentDidMount.

reactjs_reference_api.htm
Advertisements