Events
Listen to the events window and document receive, with no dependency array. An element’s own events need no hook.
On this page
Events on window
src/components/slides.tsx'use client';
import { useWindowEvent } from '@k8ordo/effects';
export function Slides({ index, onMove }: SlidesProps) {
useWindowEvent('keydown', (event) => {
if (event.key === 'ArrowRight') onMove(index + 1);
Reads the current `index`
if (event.key === 'ArrowLeft') onMove(index - 1);
});
return <Slide index={index} />;
}The listener is added to window once while the component is mounted, and removed when it unmounts.
It always calls the latest render’s handler. When index changes, nothing is added again, and the handler reads the new index. There is no dependency array to write.
The first argument is a key of WindowEventMap, and the event is typed to match: 'keydown' gives a KeyboardEvent.
Events on document
draft-editor.tsxuseDocumentEvent('visibilitychange', () => {
if (document.visibilityState === 'hidden') save(draft);
});useDocumentEvent does the same on document, typed from DocumentEventMap. The example saves the current draft when the tab is hidden.
Stopping
presentation.tsxuseWindowEvent(presenting ? 'keydown' : null, (event) => {
if (event.key === 'Escape') setPresenting(false);
});Passing null as the first argument removes the listener. The example listens for Escape only while presenting.
An element’s events
measured-list.tsx<ul
ref={(list) => {
const observer = new ResizeObserver(measure);
observer.observe(list);
return () => {
Returns the cleanup for when the element detaches
observer.disconnect();
};
}}
/>The two hooks are for the targets no element stands for, window and document. An element’s own events go in its on* props, onFullscreenChange included.
What has no on* prop goes in a ref callback, as above. Since React 19 a ref callback can return the cleanup to run when the element detaches. An IntersectionObserver or an event listener takes the same shape.