Skip to content

Commit

Permalink
mem leak fix
Browse files Browse the repository at this point in the history
  • Loading branch information
ling1726 committed May 25, 2021
1 parent d97c1a0 commit 4ef5126
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions packages/react-utilities/src/hooks/useOnClickOutside.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export type UseOnClickOutsideOptions = {
*/
export const useOnClickOutside = (options: UseOnClickOutsideOptions) => {
const { refs, callback, element, disabled, contains: containsProp } = options;
const timeoutId = React.useRef<number | undefined>(undefined);

const listener = useEventCallback((ev: MouseEvent | TouchEvent) => {
const contains: UseOnClickOutsideOptions['contains'] =
Expand Down Expand Up @@ -65,9 +66,17 @@ export const useOnClickOutside = (options: UseOnClickOutsideOptions) => {
element?.addEventListener('touchstart', conditionalHandler);
}

// Garbage collect this event after it's no longer useful to avoid memory leaks
timeoutId.current = setTimeout(() => {
currentEvent = undefined;
}, 1);

return () => {
element?.removeEventListener('click', conditionalHandler);
element?.removeEventListener('touchstart', conditionalHandler);

clearTimeout(timeoutId.current);
currentEvent = undefined;
};
}, [listener, element, disabled]);
};
Expand Down

0 comments on commit 4ef5126

Please sign in to comment.