useEvent Hook

Attach event listners in a more elegant way.

Implementation

Hook
import { useRef, useEffect } from 'react';

export default function useEvent({ eventName, handler, target = window }) {
  const savedHandler = useRef();

  const canUseEvent = target.document && target.document.addEventListener;

  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);

  useEffect(() => {
    if (!canUseEvent) return;

    const listner = (event) => savedHandler.current(event);

    target.addEventListener(eventName, listner);

    return () => {
      target.removeEventListener(eventName, listner);
    };
  }, [eventName, target]);
}

Make the space bigger

Get updates on what I do web development related. Early access to articles, easy-to-follow guides & tutorials, challenges, along with some other resources I'm reading and other stuff I think you'd enjoy...