From 3b1c96c8089a62d22d8bdcddc4ea92afd3b025ac Mon Sep 17 00:00:00 2001 From: Tu Nguyen Anh <92641762+TunA-Kai@users.noreply.github.com> Date: Tue, 22 Feb 2022 17:22:59 +0700 Subject: [PATCH 1/2] apply lastest ref pattern to store handler func With the old implementation, user have to use `useCallback` to store their `handler` if they don't want the event to be removed and re-added every time the component rerender. By saving the `handler` in the `savedHandler` we can remove `handler` in the dependency list of `useEffect`. Therefore user don't have to remember to memoize their function in the first place. --- lib/src/useEventListener/useEventListener.ts | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/lib/src/useEventListener/useEventListener.ts b/lib/src/useEventListener/useEventListener.ts index cc175937..3eaf1463 100644 --- a/lib/src/useEventListener/useEventListener.ts +++ b/lib/src/useEventListener/useEventListener.ts @@ -25,7 +25,11 @@ function useEventListener< element?: RefObject, ) { // Create a ref that stores handler - const savedHandler = useRef() + const savedHandler = useRef(handler) + + useLayoutEffect(() => { + savedHandler.current = handler + }); useEffect(() => { // Define the listening target @@ -34,18 +38,8 @@ 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) @@ -53,7 +47,7 @@ function useEventListener< return () => { targetElement.removeEventListener(eventName, eventListener) } - }, [eventName, element, handler]) + }, [eventName, element]) } export default useEventListener From d57977b1f651de8995cb731c54ecd81d05bb22ea Mon Sep 17 00:00:00 2001 From: Tu Nguyen Anh <92641762+TunA-Kai@users.noreply.github.com> Date: Tue, 22 Feb 2022 18:28:11 +0700 Subject: [PATCH 2/2] Update useEventListener.ts --- lib/src/useEventListener/useEventListener.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/useEventListener/useEventListener.ts b/lib/src/useEventListener/useEventListener.ts index 3eaf1463..6d0de83a 100644 --- a/lib/src/useEventListener/useEventListener.ts +++ b/lib/src/useEventListener/useEventListener.ts @@ -29,7 +29,7 @@ function useEventListener< useLayoutEffect(() => { savedHandler.current = handler - }); + }, [handler]); useEffect(() => { // Define the listening target