useEventListener

The useEventListener Hook allows you to add and remove event listeners in a declarative way.

Here's an example:

import { useRef, useEffect } from 'react'

function useEventListener(eventName, handler, element = window) {
  // Create a ref that stores the handler
  const savedHandler = useRef()

  // Update the ref whenever the handler or element changes
  useEffect(() => {
    savedHandler.current = handler
  }, [handler])

  useEffect(() => {
    // Make sure element supports addEventListener
    const isSupported = element && element.addEventListener
    if (!isSupported) return

    // Create event listener that calls handler function stored in ref
    const eventListener = (event) => savedHandler.current(event)

    // Add event listener
    element.addEventListener(eventName, eventListener)

    // Remove event listener on cleanup
    return () => {
      element.removeEventListener(eventName, eventListener)
    }
  }, [eventName, element])
}

function MyComponent() {
  function handleClick() {
    console.log('Button clicked!')
  }

  // Call useEventListener directly in the body of MyComponent
  useEventListener('click', handleClick)

  return <button>Click me</button>
}

In this example, we define a useEventListener Hook that takes an eventName, a handler function, and an optional element to attach the event listener to. We use two useEffect

Codesandbox Example