Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

apply lastest ref pattern to useEventListener.ts #117

Merged
merged 2 commits into from
Feb 26, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 7 additions & 13 deletions lib/src/useEventListener/useEventListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ function useEventListener<
element?: RefObject<T>,
) {
// Create a ref that stores handler
const savedHandler = useRef<typeof handler>()
const savedHandler = useRef(handler)

useLayoutEffect(() => {
savedHandler.current = handler
}, [handler]);

useEffect(() => {
// Define the listening target
Expand All @@ -34,26 +38,16 @@ function useEventListener<
return
}

// Update saved handler if necessary
if (savedHandler.current !== handler) {
savedHandler.current = handler
}

// Create event listener that calls handler function stored in ref
const eventListener: typeof handler = event => {
// eslint-disable-next-line no-extra-boolean-cast
if (!!savedHandler?.current) {
savedHandler.current(event)
}
}
const eventListener: typeof handler = event => savedHandler.current(event)

targetElement.addEventListener(eventName, eventListener)

// Remove event listener on cleanup
return () => {
targetElement.removeEventListener(eventName, eventListener)
}
}, [eventName, element, handler])
}, [eventName, element])
}

export default useEventListener