-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseHoverDirty.ts
37 lines (29 loc) · 1.02 KB
/
useHoverDirty.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { RefObject, useEffect, useState } from 'react';
import { off, on } from './misc/util';
// kudos: https://usehooks.com/
const useHoverDirty = (ref: RefObject<Element>, enabled: boolean = true) => {
if (process.env.NODE_ENV === 'development') {
if (typeof ref !== 'object' || typeof ref.current === 'undefined') {
console.error('useHoverDirty expects a single ref argument.');
}
}
const [value, setValue] = useState(false);
useEffect(() => {
const onMouseOver = () => setValue(true);
const onMouseOut = () => setValue(false);
if (enabled && ref && ref.current) {
on(ref.current, 'mouseover', onMouseOver);
on(ref.current, 'mouseout', onMouseOut);
}
// fixes react-hooks/exhaustive-deps warning about stale ref elements
const { current } = ref;
return () => {
if (enabled && current) {
off(current, 'mouseover', onMouseOver);
off(current, 'mouseout', onMouseOut);
}
};
}, [enabled, ref]);
return value;
};
export default useHoverDirty;