import React , { useEffect } from 'react' ; function param { boolean } isModalOpen param { RefObject < HTMLDivElement > } modalRef param { function } closeModalFunction returns export const useCloseModalIfClickedOutside = ( { isModalOpen , modalRef , closeModalFunction , } ) : void => { useEffect ( ( ) => { const checkIfClickedOutside = ( e ) => { if ( isModalOpen && modalRef . current && ! modalRef . current . contains ( e . target as Node ) ) { closeModalFunction ( ) ; } } ; document . body . addEventListener ( 'click' , checkIfClickedOutside ) ; return ( ) => { document . body . removeEventListener ( 'click' , checkIfClickedOutside ) ; } ; } , [ isModalOpen , closeModalFunction , modalRef ] ) ; } ;