Robust useClickOutside Hook content
Created
Description
Last Edited
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
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. 