Write a useWindowEvent hook that always calls the latest handler without re-subscribing
Write useWindowEvent(type, handler). It calls handler(event) for every type event on window, while the component is on the page.
Components pass a new inline function on every render, and the handler reads their latest props and state. The hook must always call the latest handler, but it must not remove and add the listener again when only the handler changes. When type changes, it listens for the new type instead.
function Editor({ draft }) {
useWindowEvent("keydown", (event) => {
if (event.key === "s" && event.ctrlKey) saveDraft(draft);
});
return <textarea defaultValue={draft} />;
}
import { useEffect } from "react";
export function useWindowEvent(type, handler) {
// Call the latest handler for each type event on window,
// without re-subscribing when only handler changes.
}
- calls the handler with the event
- calls the latest handler after a re-render
- doesn't add the listener again when only the handler changes
- stops listening on unmount
- listens for the new type when the type changes
- a key press reads the component's latest state
- calls the handler once per event in Strict Mode
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…