jaredLunde/react-hook

useMouse() option to keep last value when out of element?

SpangleLabs opened this issue · 2 comments

Is your feature request related to a problem? Please describe.
I've got an application where some divs will resize to follow the mouse. Currently the divs retreat back to 0 when exiting the available area, would be nice to have an option where they could stay at the last value before the mouse left the area. Especially for touch devices.

Describe the solution you'd like
I would like it if there was a mouseoption I could pass, which means that after the mouse (or touch) exits the reference area, the mouse position remains at the last recorded location, rather than becoming null.

Describe alternatives you've considered
I wondered about whether I could have some state which is updated by useMouse(), or whether your useLatest() hook can do it somehow, but I haven't managed to figure that out. If there is an alternative, please do let me know

Additional context
I've not got much additional context really.

Side note: the main readme lists this hook as useMousePosition(), but the hook is useMouse()

Store the last value yourself

Ah, yeah, my bad. I was a bit too tangled and couldn't see the wood for the trees.
Figured out how to do that now:

function useMouseLatest<T extends HTMLElement = HTMLElement>(ref: React.RefObject<T> | T | null) {
    const lastMouse = useRef<MouseCoords>({x: null, y: null});
    const mouse = useMouse(ref, {
        enterDelay: 100,
        leaveDelay: 100,
    })
    if (mouse.x != null && mouse.y != null) {
        lastMouse.current = {x: mouse.x, y: mouse.y};
    }
    return lastMouse.current;
}

Works well enough for my purposes.
Thanks, sorry about that!

EDIT: switching to a useRef, which is neater