Skip to content

Commit c67b9bc

Browse files
committed
feat: useEventListener allows a function, useGlobalListener works in SSR
1 parent ec456c1 commit c67b9bc

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

src/useEventListener.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,18 @@ export default function useEventListener<
2020
T extends Element | Document | Window,
2121
K extends keyof DocumentEventMap
2222
>(
23-
element: T,
23+
eventTarget: T | (() => T),
2424
event: K,
2525
listener: EventHandler<T, K>,
2626
capture: boolean = false
2727
) {
2828
const handler = useEventCallback(listener)
2929

3030
useEffect(() => {
31-
element.addEventListener(event, handler, capture)
32-
return () => element.removeEventListener(event, handler, capture)
33-
}, [])
31+
const target =
32+
typeof eventTarget === 'function' ? eventTarget() : eventTarget
33+
34+
target.addEventListener(event, handler, capture)
35+
return () => target.removeEventListener(event, handler, capture)
36+
}, [eventTarget])
3437
}

src/useGlobalListener.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import useEventListener from './useEventListener'
2+
import { useCallback } from 'react'
23

34
type DocumentEventHandler<K extends keyof DocumentEventMap> = (
45
this: Document,
@@ -24,5 +25,7 @@ export default function useGlobalListener<K extends keyof DocumentEventMap>(
2425
handler: DocumentEventHandler<K>,
2526
capture: boolean = false
2627
) {
27-
return useEventListener(document, event, handler, capture)
28+
const documentTarget = useCallback(() => document, [])
29+
30+
return useEventListener(documentTarget, event, handler, capture)
2831
}

0 commit comments

Comments
 (0)