JAVASCRIPT
Detect Hover State of a Component
A custom React hook to easily track the hover state of any DOM element, simplifying the creation of interactive UI components like tooltips or hover effects.
import { useState, useRef } from 'react';
function useHover() {
const [hovered, setHovered] = useState(false);
const ref = useRef(null);
const handleMouseEnter = () => setHovered(true);
const handleMouseLeave = () => setHovered(false);
const hoverProps = {
onMouseEnter: handleMouseEnter,
onMouseLeave: handleMouseLeave,
};
return [ref, hovered, hoverProps];
}
// Example Usage:
// import React from 'react';
// function HoverCard() {
// const [hoverRef, isHovered, hoverProps] = useHover();
// return (
// <div
// ref={hoverRef}
// {...hoverProps}
// style={{
// width: '200px',
// height: '100px',
// backgroundColor: isHovered ? 'lightblue' : 'lightgray',
// display: 'flex',
// alignItems: 'center',
// justifyContent: 'center',
// transition: 'background-color 0.3s',
// }}
// >
// {isHovered ? 'I am hovered!' : 'Hover over me'}
// </div>
// );
// }
How it works: This custom hook provides a simple way to track whether a DOM element is currently being hovered over by the mouse. It returns a `ref` to attach to your element, the `hovered` boolean state, and an object `hoverProps` containing `onMouseEnter` and `onMouseLeave` event handlers. You spread `hoverProps` onto the target element to automatically manage the `hovered` state, making it easy to create interactive hover effects or conditional rendering.