Rooks
HooksEvent Handling

useOnHoverRef

Returns a ref that handles native mouse-enter and mouse-leave events.

About

useOnHoverRef attaches optional native mouseenter and mouseleave callbacks to an element. It is useful when native listeners are required instead of React hover props.

Example

import { useState } from "react";
import { useOnHoverRef } from "rooks";

export default function HoverStatus() {
  const [hovered, setHovered] = useState(false);
  const hoverRef = useOnHoverRef(
    () => setHovered(true),
    () => setHovered(false)
  );

  return (
    <div ref={hoverRef} style={{ padding: 24, border: "1px solid" }}>
      {hovered ? "Pointer is inside" : "Pointer is outside"}
    </div>
  );
}

Parameters

  • onMouseEnter(event): optional native mouse-event callback.
  • onMouseLeave(event): optional native mouse-event callback.

Return value

The hook returns a callback ref that accepts an HTMLElement | null.

Behavior and lifecycle

Assigning the ref stores the current element. The hook adds both native listeners when an element is present, always calls the latest callbacks, and removes the listeners when the element changes or the component unmounts.

Compatibility and accessibility

The hook listens only to mouse events, not pointer, touch, focus, or keyboard events. Never reveal essential content exclusively on hover. Mirror meaningful hover behavior with focus and an explicit control where appropriate.

On this page