componentWillUnmount and Clean up

In React, when a component is unmounted, it means that it is being removed from the DOM (Document Object Model). This can happen when the component is no longer needed, such as when navigating to a different page or when the parent component decides to remove it.

When a component is unmounted, React provides a way to perform cleanup tasks before the component is removed from the DOM. This is done through a cleanup function, also known as a “cleanup effect” or an “effect cleanup function.”

In class components, the component unmounting and cleanup is handled through the componentWillUnmount lifecycle method. This method is called automatically by React when the component is about to be unmounted.


import React, { Component } from 'react';

class MyComponent extends Component {
  componentDidMount() {
    // This method is called when the component mounts 
    console.log('Component mounted');
  }

  componentWillUnmount() {
    // This method is called when the component is about to be unmounted, when we change the page for eg, we are setting timers and listeners in react, which is single page application. for eg clean up timers, event listeners - if we dont clean up, our page will freeze after some time and page will load slow.
     console.log('Component unmounted');
    // Perform any necessary cleanup tasks here
  }

  render() {
    return <div>My Component</div>;
  }
}
2 Likes