Skip to content

Instantly share code, notes, and snippets.

@Guria
Forked from gragland/use-hover-example.js
Last active October 30, 2018 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Guria/9e020d5025dd4e5f1d3f6bcff87a947c to your computer and use it in GitHub Desktop.
Save Guria/9e020d5025dd4e5f1d3f6bcff87a947c to your computer and use it in GitHub Desktop.
React Hook recipe from https://usehooks.com
import { useRef, useState, useEffect } from 'react';
// Usage
function App() {
const [ref, isHovered] = useHover(ref);
return (
<div ref={ref}>
{isHovered ? '😁' : '☹️'}
</div>
);
}
// Hook
function useHover() {
const [value, setValue] = useState(false);
const handleMouseOver = () => setValue(true);
const handleMouseOut = () => setValue(false);
const ref = useRef(null);
useEffect(() => {
if (ref && ref.current) {
ref.current.addEventListener('mouseover', handleMouseOver);
ref.current.addEventListener('mouseout', handleMouseOut);
}
return () => {
if (ref && ref.current) {
ref.current.removeEventListener('mouseover', handleMouseOver);
ref.current.removeEventListener('mouseout', handleMouseOut);
}
};
}, []);
return [ref, value];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment