import { useRef , useEffect } from 'react' ; import type { RefObject } from 'react' ; const DEFAULT_EVENTS = [ 'mousedown' , 'touchstart' ] ; const useOnClickOutside = ( ref , onClickAway , events = DEFAULT_EVENTS ) : void => { const onClickAwayRef = useRef ( onClickAway ) ; useEffect ( ( ) => { onClickAwayRef . current = onClickAway ; } , [ onClickAway ] ) ; useEffect ( ( ) => { const onClickHandler = ( e ) : void => { const { current : el } = ref ; ! el ?. contains ( e . target as Node ) && onClickAwayRef . current ( e ) ; } ; events . forEach ( ( evt ) => document . addEventListener ( evt , onClickHandler ) ) ; return ( ) => { events . forEach ( ( evt ) => document ?. removeEventListener ( evt , onClickHandler ) ) ; } ; } , [ ref , events ] ) ; } ; export default useOnClickOutside ;