Skip to content

Commit

Permalink
fix: callback tracking reference due to closure (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
MomenSherif authored Jul 21, 2023
1 parent 713bf8e commit 21d613f
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/useClickOutside.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,28 @@ type HookConfig = {

export const useClickOutside = <T = View>(callback: () => void, config?: HookConfig): React.RefObject<T> => {
const callbackRef = React.useRef(callback);
callbackRef.current = callback;
const callbackRegisterWrapper = () => callbackRef.current();

const ref = React.useRef<T>(null);

useFocusEffect(
() => {
if (config?.triggerOnBlur === false) return;
register(ref, callbackRef.current);
register(ref, callbackRegisterWrapper);
},
() => {
if (config?.triggerOnBlur === false) return;
callbackRef.current();
callbackRegisterWrapper();
unregister(ref);
}
);
React.useEffect(() => {
register(ref, callbackRef.current);
register(ref, callbackRegisterWrapper);
return () => {
unregister(ref);
if (config?.triggerOnUnmount === false) return;
// eslint-disable-next-line react-hooks/exhaustive-deps
callbackRef.current();
callbackRegisterWrapper();
};
}, [config?.triggerOnUnmount]);

Expand Down

0 comments on commit 21d613f

Please sign in to comment.