Skip to content

Commit 5ea0fd3

Browse files
committed
feat: 🎸 Added dependencies handling for event hook
1 parent 9a52bbf commit 5ea0fd3

File tree

4 files changed

+22
-23
lines changed

4 files changed

+22
-23
lines changed

package.json

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@better-typed/react-window-hooks",
3-
"version": "0.8.0",
3+
"version": "0.9.0",
44
"author": "prc5",
55
"license": "MIT",
66
"description": "React window hooks",
@@ -89,7 +89,6 @@
8989
"useWillUnmount"
9090
],
9191
"dependencies": {
92-
"@better-typed/react-lifecycle-hooks": "^1.0.5",
93-
"mobile-detect": "^1.4.5"
92+
"@better-typed/react-lifecycle-hooks": "^1.0.5"
9493
}
9594
}

src/hooks/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
1-
export * from "./use-window-device.hook";
21
export * from "./use-window-event.hook";
32
export * from "./use-window-size.hook";

src/hooks/use-window-device.hook.ts

Lines changed: 0 additions & 9 deletions
This file was deleted.

src/hooks/use-window-event.hook.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,37 @@ type EventHandler<T extends Event = Event> = (e: T) => void;
77

88
type WindowEventHook = {
99
<K extends keyof WindowEventMap>(
10-
eventName: K,
10+
value: K | [K, AddEventListenerOptions],
1111
handler: EventHandler<WindowEventMap[K]>,
12-
options?: boolean | (AddEventListenerOptions & { disable?: boolean }),
12+
dependencies?: any[],
1313
): void;
1414
};
1515

16-
export const useWindowEvent: WindowEventHook = (eventName, handler, options) => {
16+
const unpackValue = <K extends keyof WindowEventMap>(
17+
value: K | [K, AddEventListenerOptions],
18+
): [K, AddEventListenerOptions] => {
19+
if (typeof value === "string") {
20+
return [value, {}];
21+
}
22+
return value;
23+
};
24+
25+
export const useWindowEvent: WindowEventHook = (value, handler, dependencies = []) => {
1726
const didUnmount = useRef(false);
1827
useWillUnmount(() => (didUnmount.current = true));
1928

20-
const isClient = getIsClient();
21-
2229
useDidUpdate(
2330
() => {
24-
const { disable = false, ...windowOptions } = typeof options === "object" ? options : {};
25-
if (!isClient || disable) return;
31+
const isClient = getIsClient();
32+
if (!isClient) return;
33+
34+
const [name, options] = unpackValue(value);
35+
const windowOptions = typeof options === "object" ? options : {};
2636

27-
window.addEventListener(eventName, handler, windowOptions);
28-
return () => window.removeEventListener(eventName, handler, windowOptions);
37+
window.addEventListener(name, handler, windowOptions);
38+
return () => window.removeEventListener(name, handler, windowOptions);
2939
},
30-
[eventName, options],
40+
[JSON.stringify(value), ...dependencies],
3141
true,
3242
);
3343
};

0 commit comments

Comments
 (0)