-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathEventSpy.js
More file actions
41 lines (30 loc) · 1015 Bytes
/
EventSpy.js
File metadata and controls
41 lines (30 loc) · 1015 Bytes
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
38
39
40
41
import { useCallback, useLayoutEffect, useMemo, useRef } from 'react';
import debounceFn from './debounce';
const EventSpy = ({ debounce = 200, name, onEvent, target }) => {
// We need to save the "onEvent" to ref.
// This is because "onEvent" may change from time to time, but debounce may still fire to the older callback.
const onEventRef = useRef();
onEventRef.current = onEvent;
const debouncer = useMemo(
() =>
debounceFn(event => {
const { current } = onEventRef;
current && current(event);
}, debounce),
[debounce, onEventRef]
);
const handleEvent = useCallback(
event => {
event.timeStampLow = Date.now();
debouncer(event);
},
[debouncer]
);
useLayoutEffect(() => {
target.addEventListener(name, handleEvent, { passive: true });
handleEvent({ target, type: name });
return () => target.removeEventListener(name, handleEvent);
}, [name, handleEvent, target]);
return false;
};
export default EventSpy;