Hook to attach event listeners to any target or ref safely
Components often need a listener on something React does not render: window for keyboard shortcuts, document for clicks outside a popover, a WebSocket or BroadcastChannel for messages, or a DOM node held in a ref. Writing addEventListener in an effect every time leads to the same bugs: stale handlers, listeners that are re-added on every render, and listeners that are never removed. Implement a React hook, useDomEvent, that does it correctly once.
function useDomEvent(
target: EventTarget | { current: EventTarget | null } | null | undefined,
type: string,
handler: (event: Event) => void,
options?: { capture?: boolean; passive?: boolean; enabled?: boolean },
): void
target: any EventTarget (window, document, an element, new EventTarget(), …) or a ref object whose current holds one.options.capture and options.passive default to false and are passed to addEventListener. options.enabled defaults to true.type to the target. Each event calls handler(event).target is a ref object, read ref.current when subscribing (after the element has mounted), not during render.ref.current) is null or undefined, do nothing and do not throw.options inline. A new options object with the same values must not re-subscribe.target, type, capture, passive or enabled changes, remove the old listener and add a new one.enabled is false, no listener is attached.capture flag to removeEventListener, otherwise the browser keeps the listener.function SearchShortcut({ onOpen }) {
// A new arrow function on every render: still only one listener on window.
useDomEvent(window, 'keydown', (event) => {
if (event.key === '/') onOpen();
});
return null;
}
function Popover({ open, onClose }) {
const panelRef = useRef(null);
useDomEvent(document, 'pointerdown', (event) => {
if (!panelRef.current.contains(event.target)) onClose();
}, { capture: true, enabled: open });
return <div ref={panelRef}>…</div>;
}
function UploadButton() {
const buttonRef = useRef(null);
useDomEvent(buttonRef, 'click', () => console.log('upload'));
return <button ref={buttonRef}>Upload</button>;
}
new EventTarget() as the target and count the listeners added to and removed from it, including their capture and passive options.ReactDOM.flushSync. Events are dispatched with target.dispatchEvent(...).Object.assign(window, { useDomEvent }); below “Do not edit below this line”. The tests use it to call your hook.