Created
October 29, 2018 16:44
-
-
Save vinnymac/499d9033213b51c273f3329aed19fb18 to your computer and use it in GitHub Desktop.
Use an event listener on a specific element with React Hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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