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, useEffect, useState } from 'react'
2
3function useHover<T extends HTMLElement = HTMLElement>(
4 elementRef: RefObject<T>,
5): boolean {
6 const [value, setValue] = useState<boolean>(false)
7
8 const handleMouseEnter = () => setValue(true)
9 const handleMouseLeave = () => setValue(false)
10
11 useEffect(() => {
12 const node = elementRef?.current
13
14 if (node) {
15 node.addEventListener('mouseenter', handleMouseEnter)
16 node.addEventListener('mouseleave', handleMouseLeave)
17
18 return () => {
19 node.removeEventListener('mouseenter', handleMouseEnter)
20 node.removeEventListener('mouseleave', handleMouseLeave)
21 }
22 }
23 }, [elementRef])
24
25 return value
26}
27
28export default useHover

Usage

1import React, { useRef } from 'react'
2
3import useHover from './useHover'
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}

Created:
about 1 year ago