From d91f9fbfd6f7f9a7c49a4ebe4031710151fc2b3b Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Thu, 25 Nov 2021 09:43:47 +0200 Subject: [PATCH] Add useOnGlobalEvent --- snippets/useOnGlobalEvent.md | 50 ++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 snippets/useOnGlobalEvent.md diff --git a/snippets/useOnGlobalEvent.md b/snippets/useOnGlobalEvent.md new file mode 100644 index 000000000..b9a11da65 --- /dev/null +++ b/snippets/useOnGlobalEvent.md @@ -0,0 +1,50 @@ +--- +title: useOnGlobalEvent +tags: hooks,effect,intermediate +firstSeen: 2021-12-22T05:00:00-04:00 +--- + +Executes a callback whenever an event occurs on the global object. + +- Use the `useRef()` hook to create a variable, `listener`, which will hold the listener reference. +- Use the `useRef()` hook to create a variable that will hold the previous values of the `type` and `options` arguments. +- Use the `useEffect()` hook and `EventTarget.addEventListener()` to listen to the given event `type` on the `window` global object. +- Use `EventTarget.removeEventListener()` to remove any existing listeners and clean up when the component unmounts. + +```jsx +const useOnGlobalEvent = (type, callback, options) => { + const listener = React.useRef(null); + const previousProps = React.useRef({ type, options }); + + React.useEffect(() => { + const { type: previousType, options: previousOptions } = previousProps; + + if (listener.current) { + window.removeEventListener( + previousType, + listener.current, + previousOptions + ); + } + + listener.current = window.addEventListener(type, callback, options); + previousProps.current = { type, options }; + + return () => { + window.removeEventListener(type, listener.current, options); + }; + }, [callback, type, options]); +}; +``` + +```jsx +const App = () => { + useOnGlobalEvent('mousemove', e => { + console.log(`(${e.x}, ${e.y})`); + }); + + return

Move your mouse around

; +}; + +ReactDOM.render(, document.getElementById('root')); +```