useKeyPress

Detect when a specific key is pressed.

https://www.shaktools.com/shak-hooks
Sensor

API Reference

Installation

terminal
pnpm add @shak-hooks/usehooks
import.ts
import { useKeyPress } from "@shak-hooks/usehooks";
Source: packages/react/src/useKeyPress.ts

Signature

signature.ts
export function useKeyPress(targetKey: string)

Parameters

NameTypeOptionalDefault
targetKeystringNo-

Returns

unknown

Implementation

use-key-press.ts
1import { useState, useEffect } from "react";
2
3export function useKeyPress(targetKey: string) {
4 const [keyPressed, setKeyPressed] = useState(false);
5
6 const downHandler = ({ key }: KeyboardEvent) => {
7 if (key === targetKey) {
8 setKeyPressed(true);
9 }
10 };
11
12 const upHandler = ({ key }: KeyboardEvent) => {
13 if (key === targetKey) {
14 setKeyPressed(false);
15 }
16 };
17
18 useEffect(() => {
19 window.addEventListener("keydown", downHandler);
20 window.addEventListener("keyup", upHandler);
21
22 return () => {
23 window.removeEventListener("keydown", downHandler);
24 window.removeEventListener("keyup", upHandler);
25 };
26 }, [targetKey]);
27
28 return keyPressed;
29}

Advertisement

Google Ads

Usage

example.tsx
1import { useKeyPress } from "@shak-hooks/usehooks";
2
3const result = useKeyPress("...");
4// result: unknown
5// Use values directly (React state).

Let‘s do great work together

Empowering creators with free, high-performance AI, SEO, and developer tools. Join thousands of users optimizing their workflow with Shak-Tools.

Tools10+ Free
UsersGlobal

Stay in the loop

Join our newsletter for the latest AI tools and updates.

ShakTools
© 2025 Shaktools. All Rights Reserved.Privacy Policy