import { useRef } from "react" /** * Custom hook to manage hover state across marker and InfoWindow elements. * The Google Maps InfoWindow component does not natively support hover events. * This hook provides a way to track hover state across both elements simultaneously. * * This hook solves the problem where moving from a marker to its InfoWindow * causes the InfoWindow to close prematurely. It uses a counter to track * how many elements (marker, InfoWindow) are currently being hovered over. * * When moving from marker to InfoWindow, the InfoWindow's onMouseEnter fires * before the marker's onMouseLeave, causing the counter to correctly remain > 0. * * @param onHoverChange - Callback function that receives true when hovering starts, false when it ends * @returns Object with handleMouseEnter and handleMouseLeave functions */ export function useMarkerHover(onHoverChange: (isHovering: boolean) => void) { const hoverCountRef = useRef(0) function handleMouseEnter() { hoverCountRef.current += 1 if (hoverCountRef.current >= 1) { onHoverChange(true) // In case of rapid mouse movements, or close markers/info windows, // The counter can increase beyond 2, which is unnecessary. We reset // it to 1 which works to track hover state correctly. if (hoverCountRef.current > 2) { hoverCountRef.current = 1 } } } function handleMouseLeave() { hoverCountRef.current -= 1 if (hoverCountRef.current <= 0) { onHoverChange(false) hoverCountRef.current = 0 } } return { handleMouseEnter, handleMouseLeave, } }