This example demonstrates how to add and properly clean up event listeners in a Preact functional component using the useEffect hook. A button element is referenced using useRef, and event listeners for click and mouseover events are added within useEffect. A cleanup function within the useEffect ensures that these event listeners are removed when the component unmounts, preventing memory leaks and ensuring proper resource management.
Source code viewer
import { h } from 'preact'; import { useEffect, useRef } from 'preact/hooks'; const MyComponent = () => { const buttonRef = useRef(null); useEffect(() => { const handleClick = () => { console.log('Button clicked!'); }; const handleMouseOver = () => { console.log('Mouse over button!'); }; const button = buttonRef.current; if (button) { button.addEventListener('click', handleClick); button.addEventListener('mouseover', handleMouseOver); } // Cleanup function to remove the event listeners return () => { if (button) { button.removeEventListener('click', handleClick); button.removeEventListener('mouseover', handleMouseOver); } }; }, []); // Empty dependency array means this effect runs once on mount and cleanup on unmount return ( <div> <button ref={buttonRef}>Click Me</button> </div> ); }; export default MyComponent;Programming Language: ECMAScript