UNPKG

1.29 kBJavaScriptView Raw
1import { useEffect } from 'react';
2
3/**
4 * A [React Hook]{@link https://reactjs.org/docs/hooks-intro.html} that gives
5 * you the ability to add a callback function when an event is triggered on
6 * an object.
7 *
8 * This function attaches an event listener to a target object on mount
9 * and removes the listener on unmount.
10 *
11 * See [addEventListener()]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener}
12 *
13 * @kind function
14 *
15 * @param {EventTarget} target The [EventTarget]{@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget} to attach the listener to
16 * @param {String} type The type of [Event]{@link https://developer.mozilla.org/en-US/docs/Web/Events} to listen for, e.g. 'resize', 'error', etc.
17 * @param {Function} listener A callback function that is invoked when the event is triggered
18 * @param {...any} rest Any other arguments to pass to the addEventListener() function
19 */
20export const useEventListener = (target, type, listener, ...rest) => {
21 useEffect(() => {
22 target.addEventListener(type, listener, ...rest);
23
24 // return a callback, which is called on unmount
25 return () => {
26 target.removeEventListener(type, listener, ...rest);
27 };
28 }, [listener, rest, target, type]);
29};