Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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