React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
How do you handle cleanup in useEffect?
mid LevelMost AskedCode ExampleHooks
The cleanup function in useEffect is used to clean up side effects before the component unmounts or before the effect runs again. This prevents memory leaks, stale data, and unexpected behavior.
Syntax
js
useEffect(() => {
// Setup code
return () => {
// Cleanup code
};
}, [dependencies]);
Common Cleanup Scenarios
1. Event Listeners
jsx
useEffect(() => {
const handleResize = () => {
console.log(`Window dimensions: ${window.innerWidth} x ${window.innerHeight}`);
};
window.addEventListener('resize', handleResize);
// Cleanup: remove event listener before re-running effect or on unmount
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);