Skip to content

Instantly share code, notes, and snippets.

@ivanstnsk
Last active May 24, 2020 17:55
Show Gist options
  • Save ivanstnsk/08339e994662618568b0235d3b517055 to your computer and use it in GitHub Desktop.
Save ivanstnsk/08339e994662618568b0235d3b517055 to your computer and use it in GitHub Desktop.
use Mouse Hover hook React in Typescript
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