useKeyPress.tsx 804 B

123456789101112131415161718192021222324252627282930313233
  1. import {useEffect, useState} from 'react';
  2. /**
  3. * Hook to detect when a specific key is being pressed
  4. */
  5. function useKeyPress(targetKey: React.KeyboardEvent['key']) {
  6. const [keyPressed, setKeyPressed] = useState(false);
  7. useEffect(() => {
  8. function downHandler({key}: KeyboardEvent) {
  9. if (key === targetKey) {
  10. setKeyPressed(true);
  11. }
  12. }
  13. function upHandler({key}: KeyboardEvent) {
  14. if (key === targetKey) {
  15. setKeyPressed(false);
  16. }
  17. }
  18. window.addEventListener('keydown', downHandler);
  19. window.addEventListener('keyup', upHandler);
  20. return () => {
  21. window.removeEventListener('keydown', downHandler);
  22. window.removeEventListener('keyup', upHandler);
  23. };
  24. }, [targetKey]);
  25. return keyPressed;
  26. }
  27. export default useKeyPress;