Skip to content

Instantly share code, notes, and snippets.

@vinnymac
Created October 29, 2018 16:44
Show Gist options
  • Select an option

  • Save vinnymac/499d9033213b51c273f3329aed19fb18 to your computer and use it in GitHub Desktop.

Select an option

Save vinnymac/499d9033213b51c273f3329aed19fb18 to your computer and use it in GitHub Desktop.
Use an event listener on a specific element with React Hooks
import { useEffect, useRef } from "react";
export default function useEventListener(event, callback) {
const element = useRef(null);
useEffect(() => {
element.current.addEventListener(event, callback);
return () => element.current.removeEventListener(event, callback);
}, []);
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment