Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created June 26, 2022 22:43
Show Gist options
  • Select an option

  • Save itsMapleLeaf/9d32b0463432234ed3615e53927417f0 to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/9d32b0463432234ed3615e53927417f0 to your computer and use it in GitHub Desktop.
useWindowEvent react hook
import { useEffect } from "react"
export function useWindowEvent<Event extends keyof WindowEventMap>(
event: Event,
handler: (event: WindowEventMap[Event]) => void,
options?: boolean | AddEventListenerOptions,
) {
useEffect(() => {
window.addEventListener(event, handler, options)
return () => {
window.removeEventListener(event, handler, options)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment