React Dojo

Search

Search concepts, exercises and quizzes

dom

useKeyPress

Tracks whether a specific keyboard key is currently being held down by listening to global keydown and keyup events.


useKeyPress.ts
import { useState, useEffect } from "react"

export function useKeyPress(targetKey: string): boolean {
  const [isPressed, setIsPressed] = useState(false)

  useEffect(() => {
    const handleDown = (event: KeyboardEvent) => {
      if (event.key === targetKey) setIsPressed(true)
    }
    const handleUp = (event: KeyboardEvent) => {
      if (event.key === targetKey) setIsPressed(false)
    }

    window.addEventListener("keydown", handleDown)
    window.addEventListener("keyup", handleUp)
    return () => {
      window.removeEventListener("keydown", handleDown)
      window.removeEventListener("keyup", handleUp)
    }
  }, [targetKey])

  return isPressed
}
Was this helpful?
Sign in to give feedback