Created
July 27, 2022 14:03
-
-
Save sladg/ef79d785f59964b6145d515a9f8d82b7 to your computer and use it in GitHub Desktop.
Util function for handling hover for both touch and mouse.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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