Skip to content

Instantly share code, notes, and snippets.

@JoaoTMDias
Last active April 20, 2023 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoaoTMDias/b5aeb6e02be7e6d25d5fd7f10826fc8a to your computer and use it in GitHub Desktop.
Save JoaoTMDias/b5aeb6e02be7e6d25d5fd7f10826fc8a to your computer and use it in GitHub Desktop.
React hook to use as addEventListener in React's functional components
import { useEffect } from "react";
/**
* This replaces the need for using window.addEventListener() when using react hooks.
* You use it in exactly the same way as window.addEventListener().
*
* @example
* useEvent(event, listener, useCapture)
*
* @export
* @template T
* @param {EventHandler<T>} event
* @param {(this: Window, ev: WindowEventMap[T]) => any} listener
* @param {boolean} [passive=false]
*/
export default function useEvent<T extends keyof WindowEventMap>(
event: T,
listener: (this: Window, ev: WindowEventMap[T]) => any,
passive = false,
) {
useEffect(() => {
// initiate the event handler
window.addEventListener(event, listener, passive);
// this will clean up the event every time the component is re-rendered
return function cleanup() {
window.removeEventListener(event, listener);
};
}, []);
}
@overbyte
Copy link

note this will be run on every update, removing the event listeners and adding a fresh one which breaks in ios

@JoaoTMDias
Copy link
Author

Hi @overbyte, perhaps I need to add an empty array on the useEffect

@overbyte
Copy link

yeh that's how i dealt with it

@karthikeyan3ct
Copy link

working is fine only desktop view not working mobile view

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment