useHoverOutside

This hook is designed to handle the 'mouseleave' event for a given element, which is useful for UI interactions where an action needs to be performed once the user's mouse leaves a particular area of the interface.

Overview

The hook uses the useEffect to attach and detach the event listener to the element. The event listener is only attached if the element exists (i.e., if ref.current is not null).

The dependency array of the useEffect includes only the callback function fn to ensure that the event listener is updated if the callback changes. The ref object is not included to avoid unnecessary re-attachments of the event listener due to changes in the ref object itself.

Code

import React from "react";
 
const useHoverOutside = <T extends HTMLElement>(ref: React.RefObject<T>, fn: () => void) => {
  React.useEffect(() => {
    const element = ref.current;
 
    if (element) {
      const handleMouseLeave = (event: MouseEvent) => fn();
      element.addEventListener("mouseleave", handleMouseLeave);
 
      return () => {
        element.removeEventListener("mouseleave", handleMouseLeave);
      };
    }
  }, [fn]); // Removed ref from dependency array to avoid unnecessary re-attachments
};
 
export default useHoverOutside;

API

Parameters

T - A generic parameter that extends HTMLElement to type-check the ref.

ref - A React ref object pointing to the target HTML element. () => void - A callback function to be executed when the mouse leaves the element.

Examples

const ref = useRef<HTMLDivElement>(null);
 
useHoverOutside(ref, () => {
  console.log("Mouse has left the specified element");
});