useOnEscapePress

A utility hook that calls a user-provided function when the 'Escape' key is pressed.

This 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.

Examples

Default

With callback dependencies

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.

API

Loading data for useOnEscapePress...