npm i @react-hook/hover
A React hook for tracking the hover state of DOM elements in browsers
where hovering is possible. If the browser does not support hover states
(e.g. a phone) the isHovering
value will always be false
.
Check out the example on CodeSandbox
import * as React from 'react'
import useHover from '@react-hook/hover'
const Component = (props) => {
const target = React.useRef(null)
const isHovering = useHover(target, {enterDelay: 200, leaveDelay: 200})
return <div ref={target}>{isHovering ? 'Hovering' : 'Not hovering'}</div>
}
function useHover<T extends HTMLElement>(
target: React.RefObject<T> | T | null,
options: UseHoverOptions = {}
): boolean
Argument | Type | Required? | Description |
---|---|---|---|
target | React.RefObject | T | null |
Yes | A React ref created by useRef() or an HTML element |
options | UseHoverOptions |
Yes | Configuration options for the hook. See UseHoverOptions below. |
This hook returns true
if the element in ref
is in a hover state, otherwise false
. This value
is always false
on devices that don't have hover states, i.e. phones.
Property | Type | Description |
---|---|---|
enterDelay | number | Delays setting isHovering to true for this amount in ms |
leaveDelay | number | Delays setting isHovering to false for this amount in ms |
MIT