Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Created February 19, 2019 17:35
Show Gist options
  • Save DroopyTersen/0970aa54fa6400d9d0bbe7f5e017492d to your computer and use it in GitHub Desktop.
Save DroopyTersen/0970aa54fa6400d9d0bbe7f5e017492d to your computer and use it in GitHub Desktop.
Composing Behavior with React hooks - useHover
import { useState, useRef, useEffect } from "react";
export default function useHover() {
const [isHovered, setIsHovered] = useState(false);
const hoverRef = useRef(null);
const handleMouseOver = () => setIsHovered(true);
const handleMouseOut = () => setIsHovered(false);
useEffect(
() => {
const elem = hoverRef.current;
if (elem) {
elem.addEventListener("mouseover", handleMouseOver);
elem.addEventListener("mouseout", handleMouseOut);
return () => {
elem.removeEventListener("mouseover", handleMouseOver);
elem.removeEventListener("mouseout", handleMouseOut);
};
}
},
[hoverRef.current]
); // Recall only if ref changes
return [hoverRef, isHovered];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment