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.
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.
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
isHovered starts false. Before the pointer ever touches the element, the hook reports false.true; leaving must set it back to false. A hook that only reacts to entering gets stuck true forever.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.