javascript / intermediate
Snippet
Preventing Memory Leaks with Effect Cleanup
Returning a function from useEffect allows you to clean up subscriptions or event listeners before the component unmounts or before the effect runs again.
snippet.js
javascript
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
return () => { ... }
This is the cleanup function that React executes when the component unmounts.