Skip to content

Instantly share code, notes, and snippets.

@mbelsky
Forked from gragland/use-hover-example.js
Last active February 19, 2020 19:42
Show Gist options
  • Save mbelsky/909c7a6b9bde3289e91a6448ae1a74b3 to your computer and use it in GitHub Desktop.
Save mbelsky/909c7a6b9bde3289e91a6448ae1a74b3 to your computer and use it in GitHub Desktop.
import { useRef, useState, useEffect } from 'react';
// Usage
function App() {
const [hoverRef, isHovered] = useHover();
return (
<div ref={hoverRef}>
{isHovered ? '😁' : '☹️'}
</div>
);
}
// Hook
function useHover() {
const [value, setValue] = useState(false);
const ref = useRef(null);
useEffect(
() => {
const node = ref.current;
if (node) {
const handleMouseOver = () => setValue(true);
const handleMouseOut = () => setValue(false);
node.addEventListener('mouseover', handleMouseOver);
node.addEventListener('mouseout', handleMouseOut);
return () => {
node.removeEventListener('mouseover', handleMouseOver);
node.removeEventListener('mouseout', handleMouseOut);
};
}
},
[ref.current] // Recall only if ref changes
);
return [ref, value];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment