🧹 useEffect Cleanup Function in React JS (2025)
🧹 useEffect Cleanup Function in React JS (2025)
The cleanup function in useEffect
is used to clean up side effects like subscriptions, timers, or event listeners when a component is unmounted or before the effect runs again.
🧠 Why Cleanup?
- To prevent memory leaks
- To stop timers or intervals
- To unsubscribe from services or event listeners
✅ Real Example:
import React, { useEffect, useState } from 'react';
function TimerComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCount((prev) => prev + 1);
}, 1000);
// Cleanup function
return () => {
clearInterval(interval);
console.log('Cleanup: Interval cleared!');
};
}, []); // Runs only once
return Timer: {count}
;
}
📌 What happens here?
- An interval is created to increase the count every second.
- When the component unmounts, the cleanup function clears the interval to avoid memory leaks.