Skip to content

useHover

React hook to track when an element is being hovered over.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useHover
sh
npx @novajslabs/cli add useHover
sh
pnpm dlx @novajslabs/cli add useHover

Or copy and paste the code into your project:

ts
import { useState, RefObject, useEffect } from "react";

export const useHover = (ref: RefObject<HTMLElement>) => {
  const [isHovered, setIsHovered] = useState<boolean>(false);

  const handleMouseEnter = () => setIsHovered(true);
  const handleMouseLeave = () => setIsHovered(false);

  useEffect(() => {
    const node = ref.current;

    if (node) {
      node.addEventListener("mouseenter", handleMouseEnter);
      node.addEventListener("mouseleave", handleMouseLeave);

      return () => {
        node.removeEventListener("mouseenter", handleMouseEnter);
        node.removeEventListener("mouseleave", handleMouseLeave);
      };
    }
  }, [ref]);

  return isHovered;
};
js
import { useState, useEffect } from "react";

export const useHover = (ref) => {
  const [isHovered, setIsHovered] = useState(false);

  const handleMouseEnter = () => setIsHovered(true);
  const handleMouseLeave = () => setIsHovered(false);

  useEffect(() => {
    const node = ref.current;

    if (node) {
      node.addEventListener("mouseenter", handleMouseEnter);
      node.addEventListener("mouseleave", handleMouseLeave);

      return () => {
        node.removeEventListener("mouseenter", handleMouseEnter);
        node.removeEventListener("mouseleave", handleMouseLeave);
      };
    }
  }, [ref]);

  return isHovered;
};

Requirements

React 16.8 or higher

Parameters

ref required

Type: HTMLElement

The HTML element to track.

Return values

isHovered

Type: boolean

Indicates whether the HTML element is currently hovered (true) or not (false).

Example

tsx
import { useRef } from "react";
import { useHover } from "./hooks/useHover";

const App = () => {
  const boxRef = useRef<HTMLDivElement>(null);
  const isHovered = useHover(boxRef);

  return (
    <div ref={boxRef} style={{ padding: "20px", border: "1px solid black" }}>
      {isHovered ? "Hovering..." : "Not hovering"}
    </div>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Displaying tooltip on hover
  • Highlighting table row on hover
  • Playing a video preview on hover
  • Showing an overlay on card hover

Released under the MIT License.