Skip to content

Instantly share code, notes, and snippets.

@jhsu
Created March 11, 2022 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhsu/6eb3df853a641b511039d622dd985a14 to your computer and use it in GitHub Desktop.
Save jhsu/6eb3df853a641b511039d622dd985a14 to your computer and use it in GitHub Desktop.
import { useEffect, useRef } from "react";
export function useKeyPress(key: string, handler: (evt: Event) => void) {
const eventListenerRef = useRef<(evt: KeyboardEvent) => void>();
useEffect(() => {
console.log("redefine movement");
eventListenerRef.current = (event: KeyboardEvent) => {
if (event.key === key) {
handler?.(event);
}
};
}, [key, handler]);
useEffect(() => {
const eventListener = (event: Event) => {
eventListenerRef.current?.(event as KeyboardEvent);
};
window.addEventListener("keydown", eventListener);
return () => {
window.removeEventListener("keydown", eventListener);
};
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment