← Back to Chapters

Unmounting Components

⏱️ Unmounting Components

? What is Unmounting in React?

The unmounting phase in React occurs when a component is removed from the DOM. This happens when a component is no longer needed — for example, when the user navigates away from a page or when a conditionally rendered component is hidden.

React provides lifecycle methods and hooks to perform cleanup tasks during unmounting, so that no memory leaks or unwanted behaviors occur after the component is gone.

Unmounting = Component removed + cleanup

? Key Concepts

  • Unmounting: The moment a component is removed from the DOM tree.
  • Cleanup: Stopping timers, removing event listeners, closing subscriptions, etc.
  • componentWillUnmount(): Class component lifecycle method for cleanup.
  • useEffect() cleanup function: Functional component way to run cleanup logic.
  • Goal: Prevent memory leaks and avoid running logic for components that no longer exist.

⚙️ Class Component – componentWillUnmount()

In class-based components, the componentWillUnmount() lifecycle method runs right before the component is removed from the DOM. It is the perfect place to:

  • Clear intervals and timeouts.
  • Remove event listeners.
  • Cancel network requests or subscriptions.
? View Code Example (Class Component)
// Class-based Timer that cleans up the interval in componentWillUnmount
import React from "react";

class Timer extends React.Component {
componentDidMount() {
this.interval = setInterval(() => {
console.log("Timer running...");
}, 1000);
}

componentWillUnmount() {
clearInterval(this.interval);
console.log("Timer stopped and cleaned up!");
}

render() {
return <h3>Timer Active</h3>;
}
}

export default Timer;

? Explanation

  • componentDidMount() starts an interval that logs "Timer running..." every second.
  • componentWillUnmount() clears that interval and logs a final cleanup message.
  • After unmounting, the interval no longer runs, so the console stops printing messages.

⚛️ Functional Component – Cleanup with useEffect()

In functional components, cleanup during unmounting is handled using the return function inside the useEffect() hook.

Whatever you return from the effect callback runs when the component unmounts (and also before the effect re-runs, if dependencies change).

? View Code Example (Functional Component)
// Functional Timer that uses useEffect cleanup on unmount
import { useEffect } from "react";

function Timer() {
useEffect(() => {
const interval = setInterval(() => {
console.log("Timer running...");
}, 1000);

return () => {
clearInterval(interval);
console.log("Timer stopped and cleaned up!");
};
}, []);

return <h3>Timer Active</h3>;
}

export default Timer;

? What Happens?

  1. When Timer mounts, the effect runs and starts the interval.
  2. When Timer unmounts, the cleanup function returned from useEffect() runs.
  3. The cleanup stops the interval and prints "Timer stopped and cleaned up!" once.

?️ Example: Show / Hide Timer (Mount & Unmount)

A very common pattern is to mount a component when a toggle is ON and unmount it when the toggle is OFF. The code below shows how a parent component can mount/unmount the Timer component.

? View Code Example (Parent Component)
// Parent component that mounts/unmounts the Timer using a button
import { useState } from "react";
import Timer from "./Timer";

function TimerDemo() {
const [showTimer, setShowTimer] = useState(true);

return (
<div>
<button onClick={() => setShowTimer(!showTimer)}>
{showTimer ? "Hide Timer" : "Show Timer"}
</button>
{showTimer && <Timer />}
</div>
);
}

export default TimerDemo;

? Live Output / Behaviour

  • Initially, showTimer is true, so the <Timer /> component is mounted.
  • The console prints "Timer running..." every second.
  • When you click Hide Timer, showTimer becomes false and Timer unmounts.
  • Unmounting triggers the cleanup, the interval is cleared, and logs stop appearing.

? Why Cleanup is Important

  • ✅ Prevents memory leaks from running background tasks forever.
  • ✅ Ensures that events or timers don’t continue after the component is gone.
  • ✅ Keeps performance optimized and predictable.
  • ✅ Avoids unwanted console errors or state updates on unmounted components.

? Common Cleanup Use Cases

  • ⏱️ Stopping setInterval() or setTimeout() when leaving a page.
  • ? Removing event listeners attached to DOM elements or window.
  • ? Aborting fetch requests or WebSocket connections.
  • ? Cleaning up animations, subscriptions, or observers (e.g., ResizeObserver).

? Tips & Best Practices

  • Always include a cleanup function inside useEffect() when using side effects like timers or listeners.
  • Avoid performing asynchronous state updates inside cleanup functions (component is already unmounting).
  • Use AbortController to safely cancel network requests on unmount.
  • Keep cleanup logic focused and simple — just stop background tasks or remove listeners.

? Try It Yourself

  1. Create a Timer component that uses setInterval() to log "Timer Active" every second.
  2. Use useEffect() with a cleanup return function to stop the timer when the component unmounts.
  3. Build a parent component with a Show / Hide Timer button to conditionally render the timer.
  4. Open the browser console and observe how cleanup occurs when you hide (unmount) the timer component.

Goal: Understand how React unmounts components and learn how to perform cleanup tasks using componentWillUnmount() in class components and the cleanup function in useEffect() for functional components.