12 June 2024

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
  1. import { h } from 'preact';
  2. import { useEffect, useRef } from 'preact/hooks';
  3.  
  4. const MyComponent = () => {
  5. const buttonRef = useRef(null);
  6.  
  7. useEffect(() => {
  8. const handleClick = () => {
  9. console.log('Button clicked!');
  10. };
  11.  
  12. const handleMouseOver = () => {
  13. console.log('Mouse over button!');
  14. };
  15.  
  16. const button = buttonRef.current;
  17. if (button) {
  18. button.addEventListener('click', handleClick);
  19. button.addEventListener('mouseover', handleMouseOver);
  20. }
  21.  
  22. // Cleanup function to remove the event listeners
  23. return () => {
  24. if (button) {
  25. button.removeEventListener('click', handleClick);
  26. button.removeEventListener('mouseover', handleMouseOver);
  27. }
  28. };
  29. }, []); // Empty dependency array means this effect runs once on mount and cleanup on unmount
  30.  
  31. return (
  32. <div>
  33. <button ref={buttonRef}>Click Me</button>
  34. </div>
  35. );
  36. };
  37.  
  38. export default MyComponent;
Programming Language: ECMAScript