Skip to content

shadcn.io is an independent project built on shadcn/ui

Docs

Free

useHover for React

Returns true while the pointer is over the element you pass by ref, for when a React row, card or link should show more or start work on hover.

On this page7 sections

useHover tells you whether the pointer is over an element. Give it a ref and it returns true from the moment the pointer enters until it leaves, and false the rest of the time.

Reach for it when your component has to know, not just its styles: a row that reveals details, a link that opens a preview, a slideshow that holds still while someone reads it. For the pointer's coordinates instead of a yes or no, use useMousePosition.

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

Anatomy

useHover anatomy: useHover(), ref, isHovered

Usage

import { useHover } from "@/hooks/use-hover";

Create a ref, put it on the element, and pass the same ref to the hook. Render from the boolean it returns.

"use client";

import { useRef } from "react";
import { useHover } from "@/hooks/use-hover";

export function ProfileCard() {
  const cardRef = useRef<HTMLDivElement>(null);
  const isHovered = useHover(cardRef);

  return (
    <div ref={cardRef}>
      <h3>Ada Lovelace</h3>
      <p>{isHovered ? "Wrote the first published program" : "Mathematician"}</p>
    </div>
  );
}

Show details on the hovered row

One call watches one element, so give each row a component of its own with its own ref. Every row then keeps its own hover state, and only the row the pointer enters or leaves renders again.

"use client";

import { useRef } from "react";
import { useHover } from "@/hooks/use-hover";

interface FileEntry {
  editedAt: string;
  name: string;
}

function FileRow({ file }: { file: FileEntry }) {
  const rowRef = useRef<HTMLLIElement>(null);
  const isHovered = useHover(rowRef);

  return (
    <li ref={rowRef}>
      {file.name}
      {isHovered ? <small> edited {file.editedAt}</small> : null}
    </li>
  );
}

export function FileList({ files }: { files: FileEntry[] }) {
  return (
    <ul>
      {files.map((file) => (
        <FileRow file={file} key={file.name} />
      ))}
    </ul>
  );
}

Wait before showing a preview

The value flips the instant the pointer crosses the edge, so a preview tied straight to it flashes whenever the mouse passes over on its way somewhere else. Debounce the boolean with useDebounceValue and show the preview only while both agree: it opens after 400 milliseconds of steady hover and closes as soon as the pointer leaves.

"use client";

import { useRef } from "react";
import { useDebounceValue } from "@/hooks/use-debounce-value";
import { useHover } from "@/hooks/use-hover";

export function UserLink({ name }: { name: string }) {
  const linkRef = useRef<HTMLAnchorElement>(null);
  const isHovered = useHover(linkRef);
  const [settled] = useDebounceValue(isHovered, 400);
  const showPreview = isHovered && settled;

  return (
    <span>
      <a href={`/users/${name}`} ref={linkRef}>
        @{name}
      </a>
      {showPreview ? <span role="tooltip">Open {name}'s profile</span> : null}
    </span>
  );
}

Pause a slideshow while the pointer is on it

useInterval stops ticking when its delay is null. Pass null while the slideshow is hovered and the current slide stays up for as long as someone is reading it, then the timer starts over when they move away.

"use client";

import { useRef, useState } from "react";
import { useHover } from "@/hooks/use-hover";
import { useInterval } from "@/hooks/use-interval";

const slides = ["Spring sale", "New arrivals", "Free shipping over $50"];

export function Slideshow() {
  const showRef = useRef<HTMLDivElement>(null);
  const isHovered = useHover(showRef);
  const [index, setIndex] = useState(0);

  useInterval(
    () => setIndex((current) => (current + 1) % slides.length),
    isHovered ? null : 3000
  );

  return <div ref={showRef}>{slides[index]}</div>;
}

Open on hover or keyboard focus

Someone using a keyboard never hovers, so whatever appears on hover should appear on focus too. Track focus with onFocus and onBlur on the same wrapper, which React fires when anything inside it gains or loses focus, and open while either is true.

"use client";

import { useRef, useState } from "react";
import { useHover } from "@/hooks/use-hover";

export function ApiKeyHint() {
  const wrapperRef = useRef<HTMLSpanElement>(null);
  const isHovered = useHover(wrapperRef);
  const [isFocused, setIsFocused] = useState(false);
  const open = isHovered || isFocused;

  return (
    <span
      onBlur={() => setIsFocused(false)}
      onFocus={() => setIsFocused(true)}
      ref={wrapperRef}
    >
      <button aria-describedby="api-key-hint" type="button">
        Where is my key?
      </button>
      <span hidden={!open} id="api-key-hint" role="tooltip">
        The key is shown once, right after you create it.
      </span>
    </span>
  );
}

FAQ

Should I use useHover or the CSS :hover selector?

Use CSS whenever hover only changes how something looks. A :hover rule, or Tailwind's hover: variant, costs no JavaScript, never re-renders anything and works before your scripts have loaded.

useHover is for when the component itself has to know: to render different content, to start a request, to pause a timer or to report the hover somewhere. Each visit costs two renders, one as the pointer enters and one as it leaves.

What is the difference between useHover and onMouseEnter with onMouseLeave?

Both react to the same two events, mouseenter and mouseleave, so for an element that stays on screen the result is the same as writing onMouseEnter and onMouseLeave with your own useState.

The hook saves those lines and works where all you hold is a ref, such as an element rendered by a child component that forwards it. It also covers two cases the inline handlers miss: a pointer already resting on the element when it appears, and an element removed while it was hovered.

Does useHover work on an element that is rendered conditionally?

Yes. After each render the hook checks which element the ref holds, so one that appears behind a condition, after data loads or under a new key is picked up on the render that shows it. If the pointer is already resting on that element, the value starts out true.

When the element goes away, the value drops back to false, because a removed element never gets its mouseleave. The hook notices both on its own component's next render, so they hold whenever the component that calls useHover is also the one that renders the element.

How do I add a delay before useHover changes?

There is no delay option: the value switches on mouseenter and back on mouseleave, as the events arrive. To wait, debounce the boolean. Passing it to useDebounceValue gives you a copy that changes only after the original has held steady for the delay you choose.

For something that should open after a pause but close at once, such as a link preview, show it while the live value and the debounced copy are both true.

Does useHover work on phones and touch screens?

Only partly, because a finger can't hover. After a tap, mobile browsers send mouse events for the sake of older pages, so a tap usually turns the value true, and it stays true until a tap lands somewhere else.

Treat hover as an extra on devices that have it. You can check the (hover: hover) media query with useMediaQuery before relying on it, and make sure a tap or a focus reaches the same content.

Can keyboard users trigger useHover?

No. Moving through a page with Tab never moves the pointer, so the value stays false for anyone using a keyboard. If hovering reveals something a reader needs, such as a tooltip, a menu or a row's buttons, open it on focus as well.

Keep a focus flag from onFocus and onBlur on the same element and show the content while either flag is true. React fires both for anything inside the element, so a button within it is enough.

How do I track hover on every item in a list?

Call useHover once per item, inside a component that renders a single item. Every call keeps its own state and its own two listeners, and only the row whose value changed renders again.

On a list of thousands of rows those listeners add up. Two listeners on the list itself do the same job: mouseover, reading event.target.closest("li") to find the row under the pointer, and mouseleave to clear it. useEventListener can attach both through the list's ref.

Does useHover work with Next.js and server rendering?

Yes. The hook's file is marked "use client", so call it from a client component. On the server, and in the first render in the browser, it returns false, so the markup matches and hydration has nothing to correct.

The listeners are attached in an effect once the page has hydrated, and nothing can turn the value true before that. A pointer already resting on the element at that point counts, so the value turns true right away.

API Reference

Parameters

ParameterType
elementRefReact.RefObject<HTMLElement | null>

A ref to the element to watch.

Type
React.RefObject<HTMLElement | null>

Returns

ValueType
returnsboolean

true while the pointer is over the element.