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>
);
}
function Child() {
useEffect(() => {
console.log("Component Mounted");
return () => {
console.log("Component Unmounted");
};
}, []);
return <h1>Hello React!</h1>;
}
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");
};
}, []);
The return function is called the Cleanup Function:
- When the component unmounts.
- Before the effect runs again when its dependencies change.
Top comments (0)