Skip to content

Commit 888a5cb

Browse files
committed
feat: add useHover sensor
1 parent 026f04c commit 888a5cb

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

packages/web-api-hooks/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export { default as useDocumentVisibility } from './useDocumentVisibility';
77
export { default as useEventListener } from './useEventListener';
88
export { default as useFocus } from './useFocus';
99
export { default as useGeolocation } from './useGeolocation';
10+
export { default as useHover } from './useHover';
1011
export { default as useInterval } from './useInterval';
1112
export { default as useLocalStorage } from './useLocalStorage';
1213
export { default as useMedia } from './useMedia';
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { useState } from 'react';
2+
3+
/**
4+
* Tracks hover state of an element.
5+
*
6+
* @param disallowTouch Determines whether touch gestures should be ignored.
7+
* @returns Whether the element is hovered, and props to be spread over the element under observation.
8+
*
9+
* @example
10+
* function Component() {
11+
* const [isHovered, bindHover] = useHover();
12+
* // ...
13+
* return <ElementToObserve {...bindHover} />;
14+
* }
15+
*/
16+
export default function useHover(
17+
disallowTouch = false,
18+
): [
19+
boolean,
20+
Readonly<{
21+
onMouseEnter: () => void;
22+
onMouseLeave: () => void;
23+
onTouchStart: () => void;
24+
onTouchEnd: () => void;
25+
}>,
26+
] {
27+
const [isHovered, setHovered] = useState(false);
28+
29+
return [
30+
isHovered,
31+
{
32+
onMouseEnter() {
33+
setHovered(true);
34+
},
35+
onMouseLeave() {
36+
setHovered(false);
37+
},
38+
39+
onTouchStart() {
40+
setHovered(!disallowTouch);
41+
},
42+
onTouchEnd() {
43+
setHovered(false);
44+
},
45+
},
46+
];
47+
}

0 commit comments

Comments
 (0)