useWindowEventListener
Attaches a window event listener and removes it when the component unmounts.
About
useWindowEventListener listens for a named event on the browser window. Prefer focused wrappers such as useOnWindowResize when their fixed options match the task.
Example
import { useState } from "react";
import { useWindowEventListener } from "rooks";
export default function OnlineEventCounter() {
const [events, setEvents] = useState(0);
useWindowEventListener("online", () => {
setEvents((count) => count + 1);
});
return <p>Online events observed: {events}</p>;
}Parameters
eventName: a key fromWindowEventMap.callback: called with the native window event. The hook always invokes the latest callback.listenerOptions: optionalboolean | AddEventListenerOptions; defaults to{}.isLayoutEffect: optional boolean; defaults tofalse. Set it totrueonly when subscription must happen during the layout-effect phase.
Return value
The hook returns void.
Behavior and lifecycle
The listener is attached after commit, or during the layout-effect phase when requested. Changes to the event name or listener options replace the native subscription; callback changes update a ref. Cleanup removes the active listener when configuration changes or the component unmounts.
Compatibility and accessibility
During server rendering there is no window target, so the hook performs no subscription. Event availability depends on the browser. If an event changes visible state, preserve keyboard behavior and announce only changes that are meaningful to assistive-technology users.
Related
- useDocumentEventListener targets
document. - useOnWindowResize and useOnWindowScroll use passive listeners.
- SSR and browser APIs covers browser-only subscriptions.