23 lines
500 B
TypeScript
23 lines
500 B
TypeScript
import { throttle } from 'lodash'
|
|
import { useEffect } from 'react'
|
|
|
|
export function useKeyPress(targetKey, callback) {
|
|
useEffect(() => {
|
|
const onKeyDown = throttle((event) => {
|
|
if (event.key === targetKey) {
|
|
event.preventDefault()
|
|
callback(event)
|
|
}
|
|
}, 300)
|
|
|
|
window.addEventListener('keydown', onKeyDown)
|
|
|
|
return () => {
|
|
window.removeEventListener('keydown', onKeyDown)
|
|
onKeyDown.cancel?.()
|
|
}
|
|
}, [targetKey, callback])
|
|
|
|
return null
|
|
}
|