Skip to content

Instantly share code, notes, and snippets.

@sladg
Created July 27, 2022 14:03
Show Gist options
  • Save sladg/ef79d785f59964b6145d515a9f8d82b7 to your computer and use it in GitHub Desktop.
Save sladg/ef79d785f59964b6145d515a9f8d82b7 to your computer and use it in GitHub Desktop.
Util function for handling hover for both touch and mouse.
import { useState, HTMLAttributes, useRef, useEffect } from 'react'
export interface UseHoverOptions {
mouseEnterDelayMS?: number
mouseLeaveDelayMS?: number
}
export type HoverProps = Pick<HTMLAttributes<HTMLElement>, 'onMouseEnter' | 'onMouseLeave'>
export const useHover = ({ mouseEnterDelayMS = 0, mouseLeaveDelayMS = 0 }: UseHoverOptions = {}): [boolean, HoverProps] => {
const [isHovering, setIsHovering] = useState(false)
const mouseOutTimer = useRef(null)
const mouseEnterTimer = useRef(null)
useEffect(() => {
return () => {
clearTimeout(mouseOutTimer.current)
clearTimeout(mouseEnterTimer.current)
}
})
return [
isHovering,
{
onMouseEnter: () => {
clearTimeout(mouseOutTimer.current)
mouseEnterTimer.current = setTimeout(() => setIsHovering(true), mouseEnterDelayMS)
},
onMouseLeave: () => {
clearTimeout(mouseEnterTimer.current)
mouseOutTimer.current = setTimeout(() => setIsHovering(false), mouseLeaveDelayMS)
},
},
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment