Skip to content

Instantly share code, notes, and snippets.

@ospfranco
Created July 30, 2020 06:32
Show Gist options
  • Save ospfranco/97b4ef3efd8fd4fc69dcf407d21f4d05 to your computer and use it in GitHub Desktop.
Save ospfranco/97b4ef3efd8fd4fc69dcf407d21f4d05 to your computer and use it in GitHub Desktop.
ReactJS hook for using an event listener
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