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
Callback function to be invoked when the Escape key is pressed. Receives the keyboard event as an argument.
The document to listen on for keydown events.Default:
globalThis?.documentUsage
Basic Example
With Event Prevention
Custom Document
Conditional Listening
Implementation Details
The hook:- Uses
useCallbackRefto ensure the callback doesn’t cause unnecessary effect re-runs - Adds a
keydownevent listener withcapture: trueto catch events early in the event flow - Checks if the pressed key is ‘Escape’ before invoking the callback
- 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.