Skip to content

Instantly share code, notes, and snippets.

@dmdez
Created December 8, 2022 17:13
Show Gist options
  • Save dmdez/5c31d71998988c0b1425596e56cc0987 to your computer and use it in GitHub Desktop.
Save dmdez/5c31d71998988c0b1425596e56cc0987 to your computer and use it in GitHub Desktop.
React Hook Keypress Callback
import { useEffect, useRef } from 'react';
type KeyboardRef = (event: KeyboardEvent) => void;
const useKeypress = (keys: string[], handler?: (e: KeyboardEvent) => void) => {
const eventListenerRef = useRef<KeyboardRef | null>(null);
useEffect(() => {
eventListenerRef.current = (event: KeyboardEvent) => {
if (Array.isArray(keys) ? keys.includes(event.key) : keys === event.key) {
handler?.(event);
}
};
}, [keys, handler]);
useEffect(() => {
const eventListener = (event: KeyboardEvent) => {
if ( eventListenerRef ) {
eventListenerRef.current?.(event);
}
};
window.addEventListener('keydown', eventListener);
return () => {
window.removeEventListener('keydown', eventListener);
};
}, []);
};
export default useKeypress;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment