useKeyPress.ts 696 B

123456789101112131415161718192021222324252627
  1. import { useEffect, useState } from 'react';
  2. const useKeyPress = (targetKey: string): boolean => {
  3. const [keyPressed, setKeyPressed] = useState(false);
  4. const downHandler = ({ key }: { key: string }) => {
  5. if (key === targetKey) setKeyPressed(true);
  6. };
  7. const upHandler = ({ key }: { key: string }) => {
  8. if (key === targetKey) setKeyPressed(false);
  9. };
  10. useEffect(() => {
  11. window.addEventListener('keydown', downHandler);
  12. window.addEventListener('keyup', upHandler);
  13. return () => {
  14. window.removeEventListener('keydown', downHandler);
  15. window.removeEventListener('keyup', upHandler);
  16. };
  17. }, []);
  18. return keyPressed;
  19. };
  20. export default useKeyPress;