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 { useState, useEffect, RefObject } 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 handleMouseOver = () => setValue(true)
9 const handleMouseOut = () => setValue(false)
10
11 useEffect(() => {
12 const node = elementRef?.current
13 if (node) {
14 node.addEventListener('mouseover', handleMouseOver)
15 node.addEventListener('mouseout', handleMouseOut)
16
17 return () => {
18 node.removeEventListener('mouseover', handleMouseOver)
19 node.removeEventListener('mouseout', handleMouseOut)
20 }
21 }
22 }, [elementRef])
23
24 return !!value
25}
26
27export 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:
11 months ago