Skip to main content

useHover

A custom hook that returns the hover state of a target component and allows defining actions for mouse enter and mouse leave events.


Code

🔗 View source code


Interface

typescript
const useHover: <T extends HTMLElement>({
onEnter?: (event: MouseEvent) => void,
onLeave?: (event: MouseEvent) => void,
}) => {
ref: React.RefObject<T | null>,
isHovered: boolean
}

Options

NameTypeDefaultDescription
onEnter(event: MouseEvent) => void-Callback invoked when the mouse enters the element
onLeave(event: MouseEvent) => void-Callback invoked when the mouse leaves the element

Returns

NameTypeDescription
refReact.RefObject<T | null>Ref to attach to the target element
isHoveredbooleanWhether the mouse is currently over the element

Usage

typescript
import { useHover } from '@modern-kit/react';

const Example = () => {
const [counter, setCounter] = useState(0);

const { ref, isHovered } = useHover<HTMLDivElement>({
onEnter: () => setCounter((count) => count + 1),
onLeave: () => setCounter((count) => count - 1)
});

const style = {
width: '200px',
height: '200px',
backgroundColor: 'skyBlue'
};

return (
<>
<div ref={ref} style={style}>{isHovered ? 'hover' : 'leave'}</div>
<div>{counter}</div>
</>
);
};

Example

Hover me
Enter/leave count: 0