Skip to content

62: [FEAT] Create Hook - useKeyPress()#83

Merged
DavidHDev merged 1 commit intoDavidHDev:mainfrom
Saifullah-dev:feat/62-add-useKeyPress-hook
Nov 15, 2024
Merged

62: [FEAT] Create Hook - useKeyPress()#83
DavidHDev merged 1 commit intoDavidHDev:mainfrom
Saifullah-dev:feat/62-add-useKeyPress-hook

Conversation

@Saifullah-dev
Copy link
Copy Markdown
Contributor

@Saifullah-dev Saifullah-dev commented Oct 28, 2024

Description
A hook that detects when a specific key or combination of keys is pressed.

Acceptance Criteria

  • Single Key Detection: Triggers a callback when a specified key is pressed.
  • Combination Key Detection: Supports detecting combinations of keys (e.g., Ctrl + C).
  • Event Cleanup: Ensures event listeners are removed when the component is unmounted.

Details:

  • Single and Combination Key Detection: The hook allows detection of individual key presses or key combinations (e.g., ['Control', 'Shift', 'X'] for Ctrl + Shift + X.
  • Key Management: The hook uses a Set to track keys currently pressed. It compares this set with the target key set to determine if all required keys are pressed.
  • Event Handling:
    • The keydown event adds the pressed key to the set and checks if the required keys are pressed. If all keys are pressed, the callback is triggered.
    • The keyup event removes the key from the set once it is released.
    • The blur event clears the set to avoid lingering key states when the window loses focus.
  • Cleanup on Unmount: All event listeners (keydown, keyup, blur) are removed when the component is unmounted to prevent memory leaks and unexpected behavior.
  • Memoization: The target keys are memoized for performance optimization, ensuring that the set of keys isn't recalculated on every render.

Usage

useKeyPress(['Control', 'C'], (e) => {
  console.log('Ctrl + C detected');
});

Arguments:

  1. keys (array of strings):

    • An array of key names to detect (e.g., ['Control', 'C'] for Ctrl + C).
  2. callback (function):

    • A function that runs when the specified keys are pressed.

Note: When passing keys, you must use their specific string names as recognized by the KeyboardEvent API. For instance: Use Escape instead of Esc.

Comment thread lib/hooks/useKeyPress.ts
@DavidHDev DavidHDev merged commit dc98a2d into DavidHDev:main Nov 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants