Update useEvent implementation (#19271)
Dominic Gannaway committed
Jul 7, 2020 at 14:44 UTC
98390f11f65ea32bb0f187ef420dfbfd2c9fa3bc
1 file changed
+12
-14
packages/react-interactions/events/src/dom/create-event-handle/useEvent.js
+12
-14
@@ -11,7 +11,7 @@ import * as React from 'react';
11
import * as ReactDOM from 'react-dom';
12
13
const {useLayoutEffect, useRef} = React;
14
-const {unstable_createEventHandle: createEventHandle} = ReactDOM;
14
+const {unstable_createEventHandle} = ReactDOM;
15
16
type UseEventHandle = {|
17
setListener: (
@@ -29,14 +29,12 @@ export default function useEvent(
29
priority?: 0 | 1 | 2,
30
|},
31
): UseEventHandle {
32
- const handleRef = useRef(null);
33
- let setListener;
34
- let clears;
35
- let useEventHandle;
32
+ const handleRef = useRef<UseEventHandle | null>(null);
33
+ let useEventHandle = handleRef.current;
34
37
- if (handleRef.current == null) {
38
- setListener = createEventHandle(event, options);
39
- clears = new Map();
35
+ if (useEventHandle === null) {
36
+ const setEventHandle = unstable_createEventHandle(event, options);
37
+ const clears = new Map();
38
useEventHandle = {
39
setListener(
40
target: EventTarget,
@@ -50,7 +48,7 @@ export default function useEvent(
48
clears.delete(target);
49
return;
50
}
53
- clear = setListener(target, callback);
51
+ clear = setEventHandle(target, callback);
52
clears.set(target, clear);
53
},
54
clear(): void {
@@ -61,17 +59,17 @@ export default function useEvent(
59
clears.clear();
60
},
61
};
64
- handleRef.current = {setListener, clears, useEventHandle};
65
- } else {
66
- ({setListener, clears, useEventHandle} = handleRef.current);
62
+ handleRef.current = useEventHandle;
63
}
64
65
useLayoutEffect(() => {
66
return () => {
71
- useEventHandle.clear();
67
+ if (useEventHandle !== null) {
68
+ useEventHandle.clear();
69
+ }
70
handleRef.current = null;
71
};
74
- }, []);
72
+ }, [useEventHandle]);
73
74
return useEventHandle;
75
}