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
3// See: https://usehooks-ts.com/react-hook/use-event-listener
4import { useEventListener } from '../useEventListener'
5
6function useHover<T extends HTMLElement = HTMLElement>(
7 elementRef: RefObject<T>,
8): boolean {
9 const [value, setValue] = useState<boolean>(false)
10
11 const handleMouseEnter = () => setValue(true)
12 const handleMouseLeave = () => setValue(false)
13
14 useEventListener('mouseenter', handleMouseEnter, elementRef)
15 useEventListener('mouseleave', handleMouseLeave, elementRef)
16
17 return value
18}
19
20export default useHover

Usage

1import React, { 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 »