React/Preact hook: useEventListener

Safely bind to DOM events in your components via this great hook I wrote:

// React
import { useRef, useEffect } from 'react';

// Preact
import { useRef, useEffect } from 'preact/hooks';

export function useEventListener(
eventName: string,
eventHandler: (event?: any) => void,
element = global,
options: any = {}
): void {
const cachedEventHandler = useRef(eventHandler);
const { capture, passive, once } = options;

// Keep track of event handler method changes
useEffect(() => {
cachedEventHandler.current = eventHandler;
}, [eventHandler]);

// Keep track of event name, element, and event option
// changes
useEffect(() => {
if (!(element && element.addEventListener)) {
return;
}

const eventListener = (event: Event): void =>
cachedEventHandler.current(event);

const options = { capture, passive, once };

element.addEventListener(eventName, eventListener, options);

return (): void =>
element.removeEventListener(eventName, eventListener, options);
}, [eventName, element, capture, passive, once]);
}

Published in Code


You might enjoy these as well

  1. Easy Typewriter effect/animation with Javascript
  2. React/Preact hook: usePersistedStore
  3. Using Styled components with Preact
  4. Load a specific image depending on light/dark mode
  5. Using Angular CLI with Laravel
  6. Deploy to Netlify via GitHub actions and "$ave Dat Money"
  7. Easily preserve any aspect ratio with pure CSS
  8. Easy Light and Dark mode switching with CSS