Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update useEvent implementation #19271

Merged
merged 1 commit into from Jul 7, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -11,7 +11,7 @@ import * as React from 'react';
import * as ReactDOM from 'react-dom';

const {useLayoutEffect, useRef} = React;
const {unstable_createEventHandle: createEventHandle} = ReactDOM;
const {unstable_createEventHandle} = ReactDOM;

type UseEventHandle = {|
setListener: (
Expand All @@ -29,14 +29,12 @@ export default function useEvent(
priority?: 0 | 1 | 2,
|},
): UseEventHandle {
const handleRef = useRef(null);
let setListener;
let clears;
let useEventHandle;
const handleRef = useRef<UseEventHandle | null>(null);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason we use generics for the event and target types internally, but not in this repo?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We use Scopes internally, which means that the target needs be generic to cover them too. On the web, we can stick with EventTarget, so I could simplify it on githib. Good question though!

let useEventHandle = handleRef.current;

if (handleRef.current == null) {
setListener = createEventHandle(event, options);
clears = new Map();
if (useEventHandle === null) {
const setEventHandle = unstable_createEventHandle(event, options);
const clears = new Map();
useEventHandle = {
setListener(
target: EventTarget,
Expand All @@ -50,7 +48,7 @@ export default function useEvent(
clears.delete(target);
return;
}
clear = setListener(target, callback);
clear = setEventHandle(target, callback);
clears.set(target, clear);
},
clear(): void {
Expand All @@ -61,17 +59,17 @@ export default function useEvent(
clears.clear();
},
};
handleRef.current = {setListener, clears, useEventHandle};
} else {
({setListener, clears, useEventHandle} = handleRef.current);
handleRef.current = useEventHandle;
}

useLayoutEffect(() => {
return () => {
useEventHandle.clear();
if (useEventHandle !== null) {
useEventHandle.clear();
}
handleRef.current = null;
};
}, []);
}, [useEventHandle]);

return useEventHandle;
}