In functional components, unmounting logic is handled using the useEffect hook with a cleanup function that runs when the component unmounts.
✅ Syntax:
useEffect(() => {
// Mount logic (like subscriptions, timers, etc.)
return () => {
// ✅ Cleanup logic runs on unmount
console.log('Component unmounted');
};
}, []); // empty dependency array ensures it runs only once
🔧 Example:
import { useEffect } from 'react';
function TimerComponent() {
useEffect(() => {
const timer = setInterval(() => {
console.log('Running...');
}, 1000);
return () => {
clearInterval(timer); // 🧹 cleanup on unmount
console.log('Timer cleared on unmount');
};
}, []);
return <div>Timer is running...</div>;
}
🔁 Summary:
- Use
useEffectwith an empty dependency array[]. - Return a function inside
useEffect→ it acts like acomponentWillUnmountin class components. - Common for clearing timers, unsubscribing listeners, or aborting API requests.