useHover
Easy
Prompt
Create a custom React hook called useHover
that detects when an element is being hovered over.
This hook is useful for creating hover effects, showing tooltips, or triggering actions when a user hovers over an element.
Requirements
- The hook should accept a ref object as a parameter
- The hook should return a boolean indicating whether the element is being hovered
- The hook should handle both mouseenter and mouseleave events
- The hook should properly clean up event listeners when the component unmounts
Example
function HoverComponent() {
const ref = useRef(null);
const isHovered = useHover(ref);
return (
<div
ref={ref}
style={{
padding: '20px',
backgroundColor: isHovered ? '#f0f0f0' : 'transparent'
}}
>
{isHovered ? 'Element is being hovered' : 'Hover over me'}
</div>
);
}
Playground
Hint 1
First create a state variable to track the hover state.
const [value, setValue] = useState(false);
Hint 2
Define event handler functions and use the useEffect
hook to add and remove these handlers for 'mouseenter' and 'mouseleave' events.
const handleMouseEnter = () => setValue(true);
const handleMouseLeave = () => setValue(false);
useEffect(() => {
const element = elementRef.current;
if (!element) return;
// Add event listeners for the element
// Remember to clean up on unmount
}, [elementRef]);
Solution
Explanation
The useHover
hook detects when a user hovers over a DOM element. Let's break down how it works
First, we:
- Accept a ref as a parameter
- Create a state variable to track whether the element is being hovered
- Define handler functions to update the state when hover events occur
useEffect(() => {
const element = elementRef.current;
if (!element) return;
element.addEventListener('mouseenter', handleMouseEnter);
element.addEventListener('mouseleave', handleMouseLeave);
// Clean up the event listeners when component unmounts or the ref changes
return () => {
element.removeEventListener('mouseenter', handleMouseEnter);
element.removeEventListener('mouseleave', handleMouseLeave);
};
}, [elementRef]);
Next, we use useEffect
to:
- Access the DOM element from the provided ref
- Add event listeners to the element
- Return a cleanup function that removes the event listeners when the component unmounts or the ref changes
The dependency array [elementRef]
ensures the effect runs whenever the ref changes.
return value;
Finally, we return the boolean state indicating whether the element is being hovered.
00:00