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'23import { useEventListener } from 'usehooks-ts'45function useHover<T extends HTMLElement = HTMLElement>(6 elementRef: RefObject<T>,7): boolean {8 const [value, setValue] = useState<boolean>(false)910 const handleMouseEnter = () => setValue(true)11 const handleMouseLeave = () => setValue(false)1213 useEventListener('mouseenter', handleMouseEnter, elementRef)14 useEventListener('mouseleave', handleMouseLeave, elementRef)1516 return value17}1819export default useHover
Usage
1import { useRef } from 'react'23import { useHover } from 'usehooks-ts'45export default function Component() {6 const hoverRef = useRef(null)7 const isHover = useHover(hoverRef)89 return (10 <div ref={hoverRef}>11 {`The current div is ${isHover ? `hovered` : `unhovered`}`}12 </div>13 )14}
See a way to make this page better?
Edit there »