Combining useRef with useEffect for Event Listeners
Attach an event listener to a DOM element using a ref inside useEffect, demonstrating how to manage the event listener's lifecycle in a functional component.
import React, { useEffect, useRef } from 'react';
function MyComponent() {
// Create a ref to attach to a DOM element
const myElementRef = useRef(null);
useEffect(() => {
// Function to handle the event
const handleEvent = (event) => {
console.log('Event triggered', event);
};
// Get the current element from the ref
const currentElement = myElementRef.current;
// Attach event listener to the current element
currentElement.addEventListener('click', handleEvent);
// Cleanup function to remove event listener
return () => {
currentElement.removeEventListener('click', handleEvent);
};
}, []); // Empty dependency array ensures this runs once
return (
<div ref={myElementRef}>Click me!</div>
);
}
This code imports React with hooks, defines a functional component 'MyComponent', and uses 'useRef' to create a reference to a DOM element. 'useEffect' is used to attach a 'click' event listener to that element when the component is mounted and ensure it's removed when the component unmounts to prevent memory leaks. The empty dependency array in 'useEffect' ensures the effect only runs once on mount. The 'myElementRef' is attached to a 'div' element, so when the 'div' is clicked, 'handleEvent' will log the event to the console.