Skip to content

Commit

Permalink
refactor(useKeyPress): simplify state update logic
Browse files Browse the repository at this point in the history
  • Loading branch information
vinaybadgujar102 committed Jul 18, 2024
1 parent e24f705 commit 065fff2
Showing 1 changed file with 7 additions and 16 deletions.
23 changes: 7 additions & 16 deletions src/hooks/useKeyPress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,24 @@ import { useEffect, useState, useCallback } from "react";
export const useKeyPress = (targetKey: string) => {
const [keyPressed, setKeyPressed] = useState(false);

const downHandler = useCallback(
const keyHandler = useCallback(
(event: KeyboardEvent) => {
if (event.key === targetKey) {
setKeyPressed(true);
}
},
[targetKey],
);

const upHandler = useCallback(
(event: KeyboardEvent) => {
if (event.key === targetKey) {
setKeyPressed(false);
setKeyPressed(event.type === "keydown");
}
},
[targetKey],
);

useEffect(() => {
window.addEventListener("keydown", downHandler);
window.addEventListener("keyup", upHandler);
window.addEventListener("keydown", keyHandler);
window.addEventListener("keyup", keyHandler);

return () => {
window.removeEventListener("keydown", downHandler);
window.removeEventListener("keyup", upHandler);
window.removeEventListener("keydown", keyHandler);
window.removeEventListener("keyup", keyHandler);
};
}, [downHandler, upHandler]);
}, [keyHandler]);

return keyPressed;
};

0 comments on commit 065fff2

Please sign in to comment.