Published on

🪝️ Enhancing User Interaction with useKeyPressFunction Hook

The useKeyPressFunction hook simplifies keyboard event handling in React components. It takes three parameters: onKeyPress, a callback function to execute when a specified key is pressed; key, which defaults to 'Escape'; and trigger, indicating whether to listen for keyup or keydown events (default is keydown).

Using useCallback, it creates a memoized keyPressFunction that checks if the pressed key matches the specified one, then calls onKeyPress. The useEffect hook adds the event listener when the component mounts and removes it on unmount, ensuring efficient cleanup. This setup allows for easy implementation of custom keyboard interactions in React applications.

import { useEffect, useCallback } from 'react';

/**
 * A hook that allows you to register a handler when a specified key is pressed
 *
 * @param onKeyPress the handler function
 * @param key the key to trigger the handler (default is 'Escape')
 * @param trigger the event type to listen for ('keyup' or 'keydown', default is 'keydown')
 */
export const useKeyPressFunction = (
  onKeyPress: (e: KeyboardEvent) => void | Promise<void>,
  key: string = 'Escape',
  trigger: 'keyup' | 'keydown' = 'keydown'
) => {
  const keyPressFunction = useCallback(
    (event: KeyboardEvent) => event.key === key && onKeyPress(event),
    [onKeyPress, key]
  );

  useEffect(() => {
    document.addEventListener(trigger, keyPressFunction);
    return () => document.removeEventListener(trigger, keyPressFunction);
  }, [keyPressFunction, trigger]);
};