DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is Unmounting in React?

Unmounting is the process of removing a component from the screen.
When a React component is removed from the UI, it is called Unmounting.

Unmounting is useful for:

  • Clearing timers (setInterval, setTimeout).
  • Removing event listeners.
  • Cleaning up subscriptions.
  • Preventing unnecessary background operations.

Example using useEffect:

import React, { useEffect, useState } from 'react';

function App() {

const [show, setShow] = useState(true);

return (
    <div>
        <button onClick={() => setShow(!show)}>
            Show / Hide
        </button>

        {show && <Child />}
    </div>
);
Enter fullscreen mode Exit fullscreen mode

}

function Child() {

useEffect(() => {
    console.log("Component Mounted");

    return () => {
        console.log("Component Unmounted");
    };

}, []);

return <h1>Hello React!</h1>;
Enter fullscreen mode Exit fullscreen mode

}

export default App;

How does it work?

Step 1: Initially, show = true.

Output:

Hello React!
Component Mounted

Click the Hide button:

  • show becomes false.
  • The Child component is removed from the screen.
  • Cleanup function executes.

Console:
Component Unmounted

Click the Show button again:

  • show becomes true.
  • Child component mounts again.
  • Mounting effect runs again.

Cleanup Function:

useEffect(() => {

console.log("Mounted");

return () => {
    console.log("Unmounted");
};
Enter fullscreen mode Exit fullscreen mode

}, []);

The return function is called the Cleanup Function:

  1. When the component unmounts.
  2. Before the effect runs again when its dependencies change.

Top comments (0)