[BUG] useHover is "stuck" on `true` value if the hovered element is removed from the DOM
Author: YossiSaadiCreated Oct 10, 2024Updated Apr 14, 2025
Labelsbug
Describe the bug
I have a scenario where, when I hover on an element (container), something else is rendered adjacent to it. This hovered container contains a button as well as more stuff, and when clicking on the button, the view changes. The issue is that if I click the button and the view changes, and therefore the hovered ref is removed.
To Reproduce
https://stackblitz.com/edit/vitejs-vite-sxroxj?file=src%2Ftest.tsx&terminal=dev
const hoverRef = useRef(null);
const isHovered = useHover<HTMLElement>(hoverRef);
{showInput ? (
<input
ref={hoverRef}
type="text"
placeholder="Hover over me"
onClick={handleClick}
/>
) : (
<button>
Now I am a button!
</button>
)}once input is hovered and showInput becomes false, isHovered would stay stuck on true
Expected behavior
I guess the hook should be familiar with the fact its ref no longer exists in the DOM?
Additional context
No response
Source: juliencrn/usehooks-ts