You need to enable JavaScript to run this app.

useKeyPress

Triggers a callback function whenever a specific keyboard key is pressed.

Source

import { useEffect, useCallback } from "react";

interface KeyPressHook {
  (key: string, callback: () => void): void;
}

const useKeyPress: KeyPressHook = function (key, callback) {
  const eventHandler = useCallback((e: KeyboardEvent) => {
    if (e.key === key) callback?.();
  }, []);

  useEffect(() => {
    window.addEventListener("keyup", eventHandler);

    return () => window.removeEventListener("keyup", eventHandler);
  }, [key, callback]);
};

Usage

useKeyPress("Escape", onClickEscape);
Favourite Books
BooksPoems
Favourite Songs
PlaylistsArtists
Favourite Shows
AnimationsSeriesAnime