Skip to content

Commit

Permalink
refactor: use key pressing
Browse files Browse the repository at this point in the history
  • Loading branch information
hyoban committed Nov 11, 2024
1 parent a0fd15f commit 52f6f21
Showing 1 changed file with 10 additions and 13 deletions.
23 changes: 10 additions & 13 deletions packages/hooks/src/useKeyPressing.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
import { useEffect, useMemo, useState } from "react"
import { useEffect, useState } from "react"

export function useKeyPressing(key: string) {
const [keysPressed, setKeysPressed] = useState<string[]>([])
const [isKeyPressed, setIsKeyPressed] = useState(false)

useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
setKeysPressed((prev) => {
if (!prev.includes(event.key)) {
return [...prev, event.key]
}
return prev
})
if (event.key === key) {
setIsKeyPressed(true)
}
}

const handleKeyUp = (event: KeyboardEvent) => {
setKeysPressed((prev) => {
return prev.filter((key) => key !== event.key)
})
if (event.key === key) {
setIsKeyPressed(false)
}
}

window.addEventListener("keydown", handleKeyDown)
Expand All @@ -26,7 +23,7 @@ export function useKeyPressing(key: string) {
window.removeEventListener("keydown", handleKeyDown)
window.removeEventListener("keyup", handleKeyUp)
}
}, [])
}, [key])

return useMemo(() => keysPressed.includes(key), [keysPressed, key])
return isKeyPressed
}

0 comments on commit 52f6f21

Please sign in to comment.