useHoverLoading saved progress…

useHover

Build a custom React hook that tells a component whether the pointer is currently over one of its elements. CSS :hover can change how something looks, but it can't tell your JavaScript that hover started or ended — sometimes you need that as state (show a tooltip, load a preview, highlight a row). useHover hands back a ref to attach to any element, plus an isHovered boolean that is true while the pointer sits over it and false otherwise.

Signature

function useHover(): [
  ref: React.RefObject<HTMLElement>, // attach to the element you want to watch
  isHovered: boolean,                // true while the pointer is over it
];

The hook returns a two-item tuple. ref goes on the element via <div ref={ref} />; isHovered re-renders the component whenever the hover state changes.

Examples

function Card() {
  const [ref, isHovered] = useHover();

  return (
    <div ref={ref}>
      {isHovered ? 'Hovering!' : 'Hover over me'}
    </div>
  );
}
// Moving the pointer onto the div shows "Hovering!"; moving it off shows the prompt again.
// isHovered starts false before any pointer interaction:
const [ref, isHovered] = useHover();
// isHovered === false

Notes

  • isHovered starts false. Before the pointer ever touches the element, the hook reports false.
  • Both directions matter. Entering the element must set it true; leaving must set it back to false. A hook that only reacts to entering gets stuck true forever.
  • The ref is stable. It's the same object every render, so React keeps pointing it at the same DOM node.
  • Clean up after yourself. The listeners you attach must be removed when the element unmounts, so they don't keep firing into a component that's gone.
  • ref.current is null until mount. React only fills the ref after the element is committed to the DOM, so any listener wiring has to happen after that point.
Loading editor…