useHover
Track whether an element is being hovered over with useHover.
Install:
npm i @uidotdev/usehooks
Description:
The useHover hook allows you to track whether an element is being hovered over or not. The hook returns a reference to attach to the target element and the current hovering status, enabling you to apply conditional rendering or perform any desired actions based on the hover state.
Return Value
The useHover
hook returns an array with the following elements:
Index | Type | Description |
---|---|---|
0 | ref | A ref object that can be attached to the element intended to be hovered. |
1 | boolean | A boolean value indicating whether the element is currently being hovered. |
Demo:
Example:
import * as React from "react";
import { useHover } from "@uidotdev/usehooks";
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>
);
}