Skip to main content

useEventListener

// window (the default), document, or an element ref; the event type is checked against it
function useEventListener<K extends keyof WindowEventMap>(
type: K,
handler: (event: WindowEventMap[K]) => void,
options?: EventListenerHookOptions & { target?: Window },
): void;
function useEventListener<K extends keyof DocumentEventMap>(
type: K,
handler: (event: DocumentEventMap[K]) => void,
options: EventListenerHookOptions & { target: Document },
): void;
function useEventListener<K extends keyof HTMLElementEventMap>(
type: K,
handler: (event: HTMLElementEventMap[K]) => void,
options: EventListenerHookOptions & { target: RefObject<HTMLElement | null> },
): void;

interface EventListenerHookOptions {
enabled?: boolean; // defaults to true
capture?: boolean;
passive?: boolean;
once?: boolean;
}

Adds an event listener for as long as the component is mounted. The handler receives the right event type (KeyboardEvent for "keydown", and so on), and an event name the target doesn't have is a compile error. The latest handler is always called without re-subscribing, so inline functions are fine. The listener moves when the ref's element, type or options change, and { enabled: false } removes it.

Live demo​

1. Using the hooks. These terms are only a demo, so there is nothing to agree to here.

2. Your content. These terms are only a demo, so there is nothing to agree to here.

3. Honey. These terms are only a demo, so there is nothing to agree to here.

4. Changes to these terms. These terms are only a demo, so there is nothing to agree to here.

5. Contact. These terms are only a demo, so there is nothing to agree to here.

Example​

import { useRef, useState } from "react";
import { useEventListener } from "react-honey-hooks";

function Gallery({ onClose }: { onClose: () => void }) {
const [scrolled, setScrolled] = useState(false);
const listRef = useRef<HTMLUListElement>(null);

useEventListener("keydown", (event) => {
if (event.key === "Escape") onClose();
});
useEventListener(
"scroll",
() => {
setScrolled((listRef.current?.scrollTop ?? 0) > 0);
},
{ target: listRef, passive: true },
);

return (
<ul ref={listRef} className={scrolled ? "with-shadow" : undefined}>
{/* … */}
</ul>
);
}