javascript / intermediate
Snippet
Cleaning up Event Listeners in useEffect
Returning a function from useEffect acts as a cleanup mechanism, preventing memory leaks by removing listeners when the component unmounts.
snippet.js
1
2
3
4
5
6
7
8
useEffect(() => {const handleResize = () => console.log(window.innerWidth);window.addEventListener('resize', handleResize);return () => {window.removeEventListener('resize', handleResize);};}, []);
react
Breakdown
1
window.addEventListener('resize', ...)
Registers a global event listener when the component mounts.
2
return () => { ... }
The cleanup function that React calls before the component is destroyed.
3
window.removeEventListener(...)
Safely detaches the listener to free up system resources.