Created
July 30, 2020 06:32
-
-
Save ospfranco/97b4ef3efd8fd4fc69dcf407d21f4d05 to your computer and use it in GitHub Desktop.
ReactJS hook for using an event listener
This file contains 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
export function useEventListener(eventName: string, handler: () => void) { | |
let savedHandler = useRef<() => void>() | |
useEffect(() => { | |
savedHandler.current = handler | |
}, [handler]) | |
useEffect(() => { | |
let eventListener = () => savedHandler.current?.() | |
[Your event emitter here].addListener(eventName, eventListener) | |
return () => { | |
[Your event emitter here].removeListener(eventName, eventListener) | |
} | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment