useHover()

React UI sensor hook that determine if the mouse element is in the hover element using Javascript Typescript instead CSS. This way you can separate the logic from the UI.

The Hook

1import { RefObject, useState } from 'react'
2
3import { useEventListener } from 'usehooks-ts'
4
5function useHover<T extends HTMLElement = HTMLElement>(
6 elementRef: RefObject<T>,
7): boolean {
8 const [value, setValue] = useState<boolean>(false)
9
10 const handleMouseEnter = () => setValue(true)
11 const handleMouseLeave = () => setValue(false)
12
13 useEventListener('mouseenter', handleMouseEnter, elementRef)
14 useEventListener('mouseleave', handleMouseLeave, elementRef)
15
16 return value
17}
18
19export default useHover

Usage

1import { useRef } from 'react'
2
3import { useHover } from 'usehooks-ts'
4
5export default function Component() {
6 const hoverRef = useRef(null)
7 const isHover = useHover(hoverRef)
8
9 return (
10 <div ref={hoverRef}>
11 {`The current div is ${isHover ? `hovered` : `unhovered`}`}
12 </div>
13 )
14}

Edit on CodeSandbox

See a way to make this page better?
Edit there »