Adds an event listener for the specified event type on the given element.
useRef()
hook to create a ref that will hold the handler
.useEffect()
hook to update the value of the savedHandler
ref any time the handler
changes.useEffect()
hook to add an event listener to the given element and clean up when unmounting.el
, to use the Window
by default.const useEventListener = (type, handler, el = window) => {
const savedHandler = React.useRef();
React.useEffect(() => {
savedHandler.current = handler;
}, [handler]);
React.useEffect(() => {
const listener = e => savedHandler.current(e);
el.addEventListener(type, listener);
return () => {
el.removeEventListener(type, listener);
};
}, [type, el]);
};
const MyApp = () => {
const [coords, setCoords] = React.useState({ x: 0, y: 0 });
const updateCoords = React.useCallback(
({ clientX, clientY }) => {
setCoords({ x: clientX, y: clientY });
},
[setCoords]
);
useEventListener('mousemove', updateCoords);
return (
<p>Mouse coordinates: {coords.x}, {coords.y}</p>
);
};
ReactDOM.render(<MyApp />, document.getElementById('root'));
Would you like to help us improve 30 seconds of code?Take a quick survey
React, Hooks
Listens for changes in the pressed state of a given key.
React, Hooks
Observes visibility changes for a given element.
React, Hooks
Dynamically loads an external script.