useHover React hook
A comparison of approaches to a useHover hook
Introduction
There are quite a few different ways of implementing a useHover Hook, e.g.
It’s also worth noting the importance of reading all the basics of hooks, especially Rules of Hooks, before getting too lost in these details or trying to implement your own useHover hook.
Main points
Event type for bind
There are 3 types of event that you can bind :
- SyntheticEvent (onMouseOver, onMouseLeave)
- native with bubble up (mouseover, mouseout)
- native without bubble up (mouseenter, mouseleave)
An overview of the 2 native approaches can be found on Quirks mode:
In general you want to use mouseenter and mouseleave instead of mouseover and mouseout.
The hooks that use the native events with bubble up all cause lots of unnecessary renders/commits.
Refs
- user provides a ref (react-use dirty)
- hook returns a ref (use-hooks)
- hook internally clones the passed element (react-use)
- hook returns props to bind to a DOM element (react-hooks-lib)
Internally cloning the passed element seemed to be restrictive when trying to combine the hook with useState inside a parent hook.
When returning props to bind to a DOM element, you need to ensure these functions don’t change every time the hook fires, causing unnecessary renders.
Sandbox
Try them out here:
react-use
How it works: cloneElement
react-use, ‘useHoverDirty
’
How it works: useEffect, ref
The difference is explained here.
usehooks.com
How it works: useRef, useEffect
usehooks.com (gragland version)
How it works: useCallback, useRef
Alternate version that supports changing the element that hoverRef is applied
(from “Also check out” link on usehooks.com)
react-hooks-lib
How it works: returns onMouseEnter, onMouseLeave in bind object.
Also uses this technique: use-events