Skip to content

Commit 473aa11

Browse files
Fix useOnClickOutside deps
1 parent 21b8da9 commit 473aa11

1 file changed

Lines changed: 20 additions & 17 deletions

File tree

‎src/hooks/useOnClickOutside.ts‎

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,31 @@ export default function useOnClickOutside<TRef extends HTMLElement>({
1212
}) {
1313
const ref = useRef<TRef>(null);
1414

15-
useEffect(() => {
16-
if (!ref.current) return;
15+
useEffect(
16+
() => {
17+
if (!ref.current) return;
1718

18-
function handleClickOutside(event: Event) {
19-
if (ref.current && !ref.current.contains(event.target as Node)) {
20-
onClick();
19+
function handleClickOutside(event: Event) {
20+
if (ref.current && !ref.current.contains(event.target as Node)) {
21+
onClick();
22+
}
2123
}
22-
}
2324

24-
function handleKeyDown(event: KeyboardEvent) {
25-
if (event.key === "Escape") {
26-
onClick();
25+
function handleKeyDown(event: KeyboardEvent) {
26+
if (event.key === "Escape") {
27+
onClick();
28+
}
2729
}
28-
}
2930

30-
document.addEventListener("click", handleClickOutside);
31-
document.addEventListener("keydown", handleKeyDown);
32-
return () => {
33-
document.removeEventListener("click", handleClickOutside);
34-
document.removeEventListener("keydown", handleKeyDown);
35-
};
36-
}, [onClick, deps]);
31+
document.addEventListener("click", handleClickOutside);
32+
document.addEventListener("keydown", handleKeyDown);
33+
return () => {
34+
document.removeEventListener("click", handleClickOutside);
35+
document.removeEventListener("keydown", handleKeyDown);
36+
};
37+
},
38+
([onClick] as unknown[]).concat(deps)
39+
);
3740

3841
return ref;
3942
}

0 commit comments

Comments
 (0)