Executes a callback whenever an event occurs on the global object.
useRef()
hook to create a variable, listener
, which will hold the listener reference.useRef()
hook to create a variable that will hold the previous values of the type
and options
arguments.useEffect()
hook and EventTarget.addEventListener()
to listen to the given event type
on the Window
global object.EventTarget.removeEventListener()
to remove any existing listeners and clean up when the component unmounts.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]);
};
const App = () => {
useOnGlobalEvent('mousemove', e => {
console.log(`(${e.x}, ${e.y})`);
});
return <p>Move your mouse around</p>;
};
ReactDOM.render(<App />, document.getElementById('root'));
Would you like to help us improve 30 seconds of code?Take a quick survey
React, Hooks
Executes a callback whenever the window is scrolled.
React, Hooks
Executes a callback whenever the window is resized.
React, Hooks
Executes a callback immediately after a component is updated.