A simple utility Hook that calls a user-provided function when the `Escape` key is pressed.

useOnEscapePress is a simple utility Hook that calls a user-provided function when the Escape key is pressed. The hook sets up keydown event listener on window.document and executes the user-provided function if these conditions are met:

  1. The Escape key was pressed
  2. The preventDefault method has not yet been called on the event object.

Furthermore, unlike the normal behavior for multiple event listeners existing on the same DOM Node, if multiple useOnEscapePress hooks are active simultaneously, the callbacks will occur in reverse order. In other words, if a parent component and a child component both call useOnEscapePress, when the user presses Escape, the child component's callback will execute, followed by the parent's callback. Each callback has the chance to call .preventDefault() on the event to prevent further callbacks.


Similar to useCallback, useOnEscapePress takes a React.DependencyList as its second argument. These are the dependencies used to memoize the callback. Failing to provide the correct dependency list can result in degraded performance. If this argument is omitted, we will assume that the callback is already memoized. In the example below, that memoization occurs in DemoComponent with a call to React.useCallback, so OverlayDemo does not need to pass a dependency list.



onEscape(event: KeyboardEvent) => voidFunction to call when user presses the Escape key
callbackDependenciesReact.DependencyListArray of dependencies for memoizing the given callback