Skip to content

Commit

Permalink
refactor(use-click-outside): use callback ref intead of useEffect
Browse files Browse the repository at this point in the history
  • Loading branch information
Saya authored and Saya committed Dec 27, 2024
1 parent f3f85a3 commit 5db34d9
Showing 1 changed file with 5 additions and 9 deletions.
14 changes: 5 additions & 9 deletions src/use-click-outside/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import 'client-only';
import type { RefObject } from 'react';
import { useRef, useEffect } from 'react';
import { useCallback } from 'react';
import type { RefCallback } from 'react';

export function useClickOutside<T extends HTMLElement>(cb: () => void): RefObject<T> {
const ref = useRef<T>(null);

useEffect(() => {
export function useClickOutside<T extends HTMLElement>(cb: () => void): RefCallback<T> {
return useCallback((node) => {
const handleClick = ({ target }: MouseEvent) => {
if (target && ref.current && !ref.current.contains(target as Node)) {
if (target && node && !node.contains(target as Node)) {
cb();
}
};
Expand All @@ -16,6 +14,4 @@ export function useClickOutside<T extends HTMLElement>(cb: () => void): RefObjec
document.removeEventListener('click', handleClick);
};
}, [cb]);

return ref;
}

0 comments on commit 5db34d9

Please sign in to comment.