import { useRef , useEffect , RefObject } from 'react' ; export default function useEventListener < T extends HTMLElement = HTMLDivElement , E = Event > ( eventName , handler , element ? ) { const savedHandler = useRef < ( event : E ) => void > ( ) ; useEffect ( ( ) => { const targetElement = element ?. current || window ; if ( ! ( targetElement && targetElement . addEventListener ) ) { return ; } if ( savedHandler . current !== handler ) { savedHandler . current = handler ; } const eventListener = ( event ) => { if ( ! ! savedHandler ?. current ) { savedHandler . current ( event ) ; } } ; targetElement . addEventListener ( eventName , eventListener ) ; return ( ) => { targetElement . removeEventListener ( eventName , eventListener ) ; } ; } , [ eventName , element , handler ] ) ; }