import { useEffect } from 'react' ; export function useOnClickOutside ( ref , handler ) { useEffect ( ( ) => { const listener = ( ev ) => { if ( ev . target !== null && ref . current !== null && ! ref . current . contains ( ev . target as Node ) ) { handler ( ev ) ; } } ; let ownerDocument = null ; let timeoutID = window . setTimeout ( ( ) => { timeoutID = 0 ; ownerDocument = ref . current !== null ? ref . current . ownerDocument : window . document ; ownerDocument . addEventListener ( 'mousedown' , listener ) ; ownerDocument . addEventListener ( 'touchstart' , listener ) ; } , 0 ) ; return ( ) => { if ( timeoutID > 0 ) { clearTimeout ( timeoutID ) ; } if ( ownerDocument !== null ) { ownerDocument . removeEventListener ( 'mousedown' , listener ) ; ownerDocument . removeEventListener ( 'touchstart' , listener ) ; } } ; } , [ ref , handler ] ) ; }