Skip to content

useHover

Hook that determines whether the item is hovered or not and handles state hovers.

Demo

INFO

The component renders a paragraph element with some text to which is attacched a ref used for useHover hook that returns if element is hovered or not. This value is rendered into another paragraph element.

When mouse is hovered paragraph element, status changes to true.

Loading demo…
Show source code
tsx
import { useRef } from "react"
import { useHover } from "../../../..";

export const UseHover = () => {
	const pRef = useRef<HTMLParagraphElement>(null);
	const hover = useHover(pRef);

	return (
		<div>
			<p>Is hover: {hover ? "hover" : "not hover"}</p>
			<p ref={pRef}>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Id delectus deserunt atque! Est id voluptatem sint accusamus non doloribus totam nobis nostrum provident facilis eos eum, placeat consequatur minus quidem.</p>
		</div>
	);
}

Types

UseHoverProps

Parameters accepted by useHover.

PropertyTypeRequiredDescription
targetRefObject<HTMLElement> \| HTMLElementThe element to monitor for hover state. Accepts either a React RefObject&lt;HTMLElement&gt; or a direct HTMLElement reference.
optsUseHoverOptionsOptional configuration for event callbacks and return value behaviour.

UseHoverOptions

Options accepted by useHover.

PropertyTypeRequiredDescription
onEnter(evt: Event) => voidCalled when the pointer enters the target element (pointerenter event).
onChange(isHover: boolean) => voidCalled whenever the hover state changes. Receives true when the pointer enters and false when it leaves.
onLeave(evt: Event) => voidCalled when the pointer leaves the target element (pointerleave event).
returnValuebooleanControls whether the hook returns the current hover state as a boolean: - true — The hook returns a reactive boolean that is true while the pointer is over the target and false otherwise. - false (default) — The hook returns void. Use this when you only need the callbacks and want to avoid unnecessary re-renders.

Released under the MIT License.