Docs
Hover

Hover

Track whether an element is being hovered over

About

The useHover hook allows you to track whether an element is being hovered over. It returns a reference to attach to the target element and the current hovering status, enabling conditional rendering or actions based on the hover state.

Return Values

IndexTypeDescription
0refA ref object that can be attached to the element intended to be hovered.
1booleanA boolean value indicating whether the element is currently being hovered.

Installation

Run the following command:

npx scriptkavi-hooks@latest add hover

Usage

import { useHover } from "@/hooks/hover"
import * as React from "react"
 
function getRandomColor() {
  const colors = ["green", "blue", "purple", "red", "pink"]
  return colors[Math.floor(Math.random() * colors.length)]
}
 
export default function App() {
  const [ref, hovering] = useHover()
 
  const backgroundColor = hovering
    ? `var(--${getRandomColor()})`
    : "var(--charcoal)"
 
  return (
    <section>
      <h1>useHover</h1>
      <article ref={ref} style={{ backgroundColor }}>
        Hovering? {hovering ? "Yes" : "No"}
      </article>
    </section>
  )
}