Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Created January 9, 2026 13:22
Show Gist options
  • Select an option

  • Save MarekZeman91/d86d96e263cfb12735747bb6b8549a15 to your computer and use it in GitHub Desktop.

Select an option

Save MarekZeman91/d86d96e263cfb12735747bb6b8549a15 to your computer and use it in GitHub Desktop.
import { useEffect } from 'react'
import { useFunction } from './useFunction'
/**
* Hook to use native event listener
* @param eventName
* @param listener Does not have to be memorized
*/
export function useNativeEvent<K extends keyof GlobalEventHandlersEventMap>(
eventName: K,
listener: (event: GlobalEventHandlersEventMap[K]) => void
) {
const callback = useFunction(listener)
useEffect(() => {
window.addEventListener(eventName, callback)
return () => window.removeEventListener(eventName, callback)
}, [eventName, callback])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment