Cleaning up Event Listeners with useEffect
Give an example of adding and removing event listeners with useEffect, explaining how React 18 automatically cleans up event listeners to prevent memory leaks.
import { useEffect } from 'react';
function ExampleComponent() {
useEffect(() => {
const handleResize = () => {
// Do something on resize
console.log('Window resized.');
};
// Add event listener
window.addEventListener('resize', handleResize);
// Returned function will be called on component unmount
return () => {
// Remove event listener
window.removeEventListener('resize', handleResize);
};
}, []); // Empty array ensures the effect runs only once on mount
return (
// Your component JSX here
);
}
In this code, useEffect is used to add an event listener to the window object when the component mounts. The effect returns a cleanup function that removes the event listener, preventing memory leaks when the component unmounts. React 18 will automatically call this cleanup function when necessary.