EventIntermediateBrowser APIshooks/events/useKeyCombination.ts

useKeyCombination

Handle Ctrl/Cmd combos.

Import

TypeScript
import { useKeyCombination } from '@/hooks';

API

Signature

useKeyCombination(combo, handler, options?)

When to use

Use useKeyCombination instead of re-implementing the same pattern in multiple components.

SSR / Next.js

No-ops until document/window exist.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useKeyCombination
Editor
function CommandK() {
  useKeyCombination({ key: 'k', ctrl: true }, () => {
    console.log('open command palette');
  });
  return <p>Ctrl/Cmd + K</p>;
}
Preview

Implementation source

Full library source for useKeyCombination — copy into your project when you are not installing a package yet.

hooks/events/useKeyCombination.ts
import { useEffect, useRef } from 'react';
import { isBrowser } from '../utility/isBrowser';
import { useLatest } from '../utility/useLatest';

export interface KeyCombination {
  key: string;
  /** Require Ctrl (also accepts Meta when `meta` is not set). */
  ctrl?: boolean;
  meta?: boolean;
  alt?: boolean;
  shift?: boolean;
}

function matchesCombo(event: KeyboardEvent, c: KeyCombination): boolean {
  const keyMatch =
    event.key.toLowerCase() === c.key.toLowerCase() ||
    event.code.toLowerCase() === c.key.toLowerCase();
  if (!keyMatch) return false;

  const alt = !!c.alt;
  const shift = !!c.shift;
  const ctrl = !!c.ctrl;
  const meta = !!c.meta;

  if (event.altKey !== alt) return false;
  if (event.shiftKey !== shift) return false;

  if (ctrl && !meta) {
    // Cross-platform: Ctrl on Windows/Linux, Cmd on macOS
    return event.ctrlKey || event.metaKey;
  }
  if (event.ctrlKey !== ctrl) return false;
  if (event.metaKey !== meta) return false;
  return true;
}

/** Detect a key combination (e.g. Ctrl/Cmd + K). */
export function useKeyCombination(
  combo: KeyCombination | KeyCombination[],
  handler: (event: KeyboardEvent) => void,
  options: { enabled?: boolean; preventDefault?: boolean } = {},
): void {
  const { enabled = true, preventDefault = true } = options;
  const handlerRef = useLatest(handler);
  const combosRef = useRef(Array.isArray(combo) ? combo : [combo]);
  combosRef.current = Array.isArray(combo) ? combo : [combo];

  useEffect(() => {
    if (!isBrowser() || !enabled) return;

    const listener = (event: KeyboardEvent) => {
      const hit = combosRef.current.some((c) => matchesCombo(event, c));
      if (!hit) return;
      if (preventDefault) event.preventDefault();
      handlerRef.current(event);
    };

    window.addEventListener('keydown', listener);
    return () => window.removeEventListener('keydown', listener);
  }, [enabled, preventDefault, handlerRef]);
}

Copy-paste example

useKeyCombination.example.tsx
'use client';

import { useKeyCombination } from '@/hooks';

export function CommandK() {
  useKeyCombination({ key: 'k', ctrl: true }, () => {
    console.log('open command palette');
  });
  return <p>Ctrl/Cmd + K</p>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Pass all relevant refs to useClickOutside (trigger + panel). Prefer useLatest for handlers.
  • Source of truth: open hooks/events/useKeyCombination.ts for implementation details