useHover

A hook to track if an element is being hovered.

Overview

useHover tracks whether the mouse cursor is hovering over a specific element. It returns a ref to attach to the target element and a boolean indicating the hover state.

Demo

Interaction

Hover State

Tracks mouse enter and leave events using a ref.

Hover Me
Move your cursor over this card.

API Reference

function useHover<T extends HTMLElement>(): [RefObject<T>, boolean]

Returns

Returns a tuple [ref, isHovered]:

  • ref: A React ref object to attach to the target element.
  • isHovered: Boolean true if hovered, false otherwise.

Usage Example

import { useHover } from 'react-hooks-ts'
 
function HoverCard() {
  const [hoverRef, isHovered] = useHover()
 
  return (
    <div ref={hoverRef} style={{ background: isHovered ? 'black' : 'white' }}>
      {isHovered ? 'Hovered!' : 'Hover Me'}
    </div>
  )
}