use-window-event

Adds event listener to window on component mount and removes it on unmount

Usage

use-window-event adds event listener to window object on component mount and removes it on unmount:

import { useEffect } from "react";
import { useWindowEvent } from "@bigcomponents/hooks";
 
const handler = (event) => console.log(event);
 
// regular way
useEffect(() => {
  window.addEventListener("keydown", handler);
  return () => window.removeEventListener("keydown", handler);
}, []);
 
// with use-window-event hook
useWindowEvent("keydown", handler);

Example

Search focus with ⌘ + K on mac or Ctrl + K on windows and linux on Bigcomponents docs website:

import { useRef } from "react";
import { useWindowEvent } from "@bigcomponents/hooks";
 
function Demo() {
  const inputRef = useRef<HTMLInputElement>();
 
  useWindowEvent("keydown", (event) => {
    if (event.code === "KeyK" && (event.ctrlKey || event.metaKey)) {
      event.preventDefault();
      inputRef.current.focus();
    }
  });
 
  return <input ref={inputRef} />;
}

Definition

Hook has exact same definition as window.addEventListener function:

function useWindowEvent<K extends keyof WindowEventMap>(
  type: K,
  listener: (this: Window, ev: WindowEventMap[K]) => any,
  options?: boolean | AddEventListenerOptions
): void;