Page cover image

Robust useClickOutside Hook

  • React
  • Front-end
  • UI
Created
Sep 8, 2022 03:45 PM
Description
Last Edited
Sep 8, 2022 03:57 PM
Tags
React
Front-end
UI

Code

import React, { useEffect } from 'react' export default function useClickOutside( ref: React.MutableRefObject<HTMLElement>, handler: (event?: MouseEvent) => void, ) { useEffect(() => { const listener = (event) => { // Do nothing if clicking ref's element or descendent elements if (!ref.current || ref.current.contains(event.target)) { return } handler(event) } document.addEventListener('mousedown', listener) document.addEventListener('touchstart', listener) return () => { document.removeEventListener('mousedown', listener) document.removeEventListener('touchstart', listener) } }, [ref, handler]) }
Parameters
Parameter
Type
Description
ref
Ref to the monitored element (e.g. a menu container)
function
Callback function to the click-outside event

Use Case

This implementation is quite robust because it doesn’t rely on observing the window object, although it costs a bit more resources due to the use of the contains() method.