Last active
May 24, 2020 17:55
-
-
Save ivanstnsk/08339e994662618568b0235d3b517055 to your computer and use it in GitHub Desktop.
use Mouse Hover hook React in Typescript
This file contains 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 { useEffect, useState, useRef } from 'react'; | |
type THook<T extends HTMLElement> = [ | |
React.RefObject<T>, | |
boolean, | |
]; | |
export const useMouseHover = <T extends HTMLElement>(): THook<T> => { | |
const [hovered, setHovered] = useState(false); | |
const ref = useRef<T>(null); | |
useEffect(() => { | |
const handleMouseOver = (): void => setHovered(true); | |
const handleMouseOut = (): void => setHovered(false); | |
const node = ref && ref.current; | |
if (node) { | |
node.addEventListener('mouseover', handleMouseOver); | |
node.addEventListener('mouseout', handleMouseOut); | |
return () => { | |
node.removeEventListener('mouseover', handleMouseOver); | |
node.removeEventListener('mouseout', handleMouseOut); | |
}; | |
} | |
}, [ref]); | |
return [ref, hovered]; | |
}; | |
// Example of usage | |
// const [buttonRef, buttonHovered] = useMouseHover<HTMLButtonElement>(); | |
// const color = buttonHovered ? 'red' : 'blue'; | |
// | |
// return ( | |
// <button | |
// ref={buttonRef} | |
// style={{ color }} | |
// > | |
// click me | |
// </button> | |
// ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment