useEscapeKey
Location: src/hooks/useEscapeKey.js
Overview
A utility hook that listens for the Escape key being pressed and invokes a callback. Commonly used alongside useClickOutside to close modals, dialogs, and popovers. Attaches a keydown listener to the document.
Signature
function useEscapeKey(
onEscape: (event: KeyboardEvent) => void,
enabled?: boolean
): void
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
onEscape | (event: KeyboardEvent) => void | Yes | Callback invoked when the Escape key is pressed. Receives the original keyboard event. |
enabled | boolean | No | Whether the listener is active. Defaults to true. Set to false to temporarily disable. |
Return Value
This hook does not return anything.
Usage
function Modal({ isOpen, onClose }) {
useEscapeKey(onClose, isOpen);
if (!isOpen) return null;
return (
<div className="modal-overlay">
<div className="modal">
<p>Press Escape to close</p>
</div>
</div>
);
}
Combined with useClickOutside
function Dialog({ onClose }) {
const ref = useClickOutside(onClose);
useEscapeKey(onClose);
return (
<div ref={ref} className="dialog">
<p>Click outside or press Escape to close</p>
</div>
);
}
Last updated: 2026-02-07