useHover

A React hook that tracks hover state of DOM elements with TypeScript support. Provides a simple interface for handling hover interactions and implementing hover effects. Includes ref-based tracking and optimized re-renders.

Live Demo

Hover me! 👋

Interactive Card

This example shows scale and shadow effects on hover

Implementation

export function useHover<T extends HTMLElement = HTMLElement>() {
  const [isHovered, setIsHovered] = useState(false);
  const ref = useRef<T>(null);

  const handleMouseEnter = useCallback(() => setIsHovered(true), []);
  const handleMouseLeave = useCallback(() => setIsHovered(false), []);

  const hoverProps = {
    onMouseEnter: handleMouseEnter,
    onMouseLeave: handleMouseLeave,
    ref,
  };

  return [isHovered, hoverProps] as const;
}

Usage

import { useHover } from '@/components/hooks/useHover';

function MyComponent() {
  const [isHovered, hoverProps] = useHover<HTMLDivElement>();

  return (
    <div {...hoverProps} className={`p-4 rounded-lg ${
      isHovered ? "bg-blue-500 text-white" : "bg-gray-100"
    }`}>
      {isHovered ? "I'm being hovered! 🎉" : "Hover me! 👋"}
    </div>
  );
}

Important Notes

Key Features

  • TypeScript support with generic types for element inference
  • Optimized performance with useCallback for event handlers
  • Simple API with convenient prop spreading
  • Automatic cleanup of event listeners
  • Zero dependencies

Use Cases

  • Interactive UI elements
  • Hover-triggered animations
  • Tooltips and popovers
  • Navigation menus
  • Interactive data visualizations

Browser Compatibility

The hook uses standard mouse events (mouseenter/mouseleave) which are widely supported across all modern browsers. For touch devices, consider implementing additional touch-specific interactions as hover states may not be appropriate.