Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.