useOnClickOutside

Here's an example of a custom hook called useOnClickOutside that detects clicks outside of a specific element:

import { useEffect } from 'react'

function useOnClickOutside(ref, handler) {
  useEffect(() => {
    const listener = (event) => {
      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])
}

export default useOnClickOutside

This custom hook takes a ref and a handler as parameters, and returns an effect that adds event listeners to the document. The handler is called when a click or touch event occurs outside of the element referenced by the ref.

To use this custom hook, you would simply call it in your functional component and pass in a ref to the element you want to detect clicks outside of, and a handler function to be called when a click occurs outside of the element:

import React, { useRef } from 'react'
import useOnClickOutside from './useOnClickOutside'

function MyComponent() {
  const ref = useRef()

  useOnClickOutside(ref, () => {
    console.log('Clicked outside!')
  })

  return (
    <div ref={ref}>
      <p>Click outside of this element to trigger the handler.</p>
    </div>
  )
}

In this example, we call the useOnClickOutside hook with a ref to the outer div element, and a handler function that logs a message to the console. When a click occurs outside of the div element, the handler function is called and logs the message to the console.

Codesandbox Example