Frontend Blocks typescript Intermediate

Keyboard Shortcut Hook

React hook to bind global keyboard shortcuts without conflicting with form inputs.

typescript
import { useEffect } from "react";

export function useHotkey(combo: string, handler: () => void) {
  useEffect(() => {
    const [mod, key] = combo.split("+");
    const listener = (e: KeyboardEvent) => {
      const target = e.target as HTMLElement;
      if (["INPUT","TEXTAREA"].includes(target.tagName)) return;
      if (mod === "ctrl" && e.ctrlKey && e.key === key) { e.preventDefault(); handler(); }
      if (mod === "meta" && e.metaKey && e.key === key) { e.preventDefault(); handler(); }
    };
    window.addEventListener("keydown", listener);
    return () => window.removeEventListener("keydown", listener);
  }, [combo, handler]);
}

Prerequisites

  • React >= 17

Pro Tips

  • → Wrap handler in useCallback to avoid re-registering on every render.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
typescript
Level
Intermediate
Read time
3 min
Published
Nov 2025
License
Commercial License

Newsletter

New modules every week, directly to your inbox.