EventIntermediateBrowser APIshooks/events/useEscapeKey.ts

useEscapeKey

Handle Escape specifically.

Import

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

API

Signature

useEscapeKey(handler, options?)

When to use

Use useEscapeKey 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 · useEscapeKey
Editor
function ModalEsc({ onClose }: { onClose: () => void }) {
  useEscapeKey(onClose);
  return <div role="dialog">Press Escape</div>;
}
Preview

Implementation source

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

hooks/events/useEscapeKey.ts
import { useKeyPress } from './useKeyPress';

/** Shortcut for Escape key press handling. */
export function useEscapeKey(
  handler: (event: KeyboardEvent) => void,
  options: { enabled?: boolean; preventDefault?: boolean } = {},
): void {
  useKeyPress('Escape', handler, {
    enabled: options.enabled,
    preventDefault: options.preventDefault,
  });
}

Copy-paste example

useEscapeKey.example.tsx
'use client';

import { useEscapeKey } from '@/hooks';

export function ModalEsc({ onClose }: { onClose: () => void }) {
  useEscapeKey(onClose);
  return <div role="dialog">Press Escape</div>;
}

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/useEscapeKey.ts for implementation details