The useEffect hook can handle component unmounting by returning a cleanup function. This cleanup function is executed when the component is about to unmount or before the effect runs again due to a change in dependencies. This is useful for cleaning up resources such as timers, subscriptions, or event listeners that were set up in the effect.
Here's how it works:
-
Return a Cleanup Function: Inside the
useEffectcallback, you can return a function. This function will be called when the component unmounts or before the effect is re-run. -
Cleanup on Unmount: When the component is removed from the DOM, React will call the cleanup function, allowing you to perform any necessary cleanup.
Here's an example:
import React from 'react';
const TimerComponent = () => {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const timer = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 1000);
// Cleanup function to clear the timer
return () => {
clearInterval(timer);
console.log('Timer cleared');
};
}, []); // Empty dependency array means this effect runs once on mount
return (
<div>
<p>Count: {count}</p>
</div>
);
};
export default TimerComponent;
In this example:
- A timer is set up using
setIntervalto increment thecountstate every second. - The cleanup function returned from
useEffectcallsclearInterval(timer)to stop the timer when the component unmounts. - This prevents memory leaks and ensures that the timer does not continue running after the component is removed from the DOM.
