Skip to main content
useEscapeKeydown is a hook that listens for Escape key presses on a document and executes a callback when detected. It’s commonly used for dismissing modals, dropdowns, and other overlay components.

Installation

Function Signature

Parameters

(event: KeyboardEvent) => void
Callback function to be invoked when the Escape key is pressed. Receives the keyboard event as an argument.
Document
The document to listen on for keydown events.Default: globalThis?.document

Usage

Basic Example

With Event Prevention

Custom Document

Conditional Listening

Implementation Details

The hook:
  1. Uses useCallbackRef to ensure the callback doesn’t cause unnecessary effect re-runs
  2. Adds a keydown event listener with capture: true to catch events early in the event flow
  3. Checks if the pressed key is ‘Escape’ before invoking the callback
  4. Cleans up the event listener when the component unmounts or dependencies change

Notes

The event listener is added with capture: true, which means it will intercept the event during the capture phase, before it reaches the target element. This ensures the Escape key is handled even if other elements prevent propagation.
The callback is wrapped with useCallbackRef, so you can safely pass inline functions or callbacks that change frequently without worrying about the effect re-running unnecessarily.