import * as React from 'react' ; import { useLatestRef } from './use-latest-ref' ; param event param handler param doc param options export function useEventListener < K extends keyof DocumentEventMap > ( event , handler , doc = typeof window !== 'undefined' ? document : null , options ? ) { const savedHandler = useLatestRef ( handler ) ; React . useEffect ( ( ) => { if ( ! doc ) return undefined ; const listener = ( event ) => { savedHandler . current ?. ( event ) ; } ; doc . addEventListener ( event , listener , options ) ; return ( ) => { doc . removeEventListener ( event , listener , options ) ; } ; } , [ event , doc , options , savedHandler ] ) ; return ( ) => { if ( savedHandler . current ) { doc ?. removeEventListener ( event , savedHandler . current as any , options ) ; } } ; }