import { throttle } from 'lodash'
import { useEffect } from 'react'

export function useKeyPress(targetKey: string, callback: CallableFunction) {
  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
}
