useKeyUp

React hook to listen for key release events with key combinations, element scoping, and typed callbacks.

pnpm add react-callback-hooks

Demo

Q
W
E
A
S
D

Press and release a key

Usage

Single key or array of keys:

import { useKeyUp } from 'react-callback-hooks'

export default function App() {
  useKeyUp('Escape', (event, key) => {
    console.log(`${key} released`)
  })

  useKeyUp(['KeyW', 'KeyA', 'KeyS', 'KeyD'], (event, key) => {
    console.log(`Stopped moving: ${key}`)
  })
}

Key combos and modifier shortcuts:

import { useKeyUp } from 'react-callback-hooks'

useKeyUp('Shift+Enter', (event) => {
  console.log('Shift+Enter released')
})

useKeyUp('CtrlOrCmd+K', (event) => {
  console.log('Shortcut released')
})

Object form with preventDefault:

useKeyUp('Escape', {
  preventDefault: true,
  onKeyUp: (event, key) => {
    closeModal()
  }
})

Scoped to a specific element:

export default function SearchBox() {
  const inputRef = useKeyUp<string, HTMLInputElement>('Enter', (event, key) => {
    console.log('Enter released in input')
  })

  return <input ref={inputRef} placeholder="Press and release Enter..." />
}

Parameters

ParameterTypeDescription
keysK | readonly K[]Single key, key combination, or an array of keys / combos to listen for.
callback(event: KeyboardEvent, key: K) => voidSimple form. Called when a matching key is released.

Object form second argument:

PropertyTypeDefaultDescription
onKeyUp(event: KeyboardEvent, key: K) => voidCallback fired on key release.
preventDefaultbooleanfalseWhen true, calls event.preventDefault() when the key matches.

Return Values

Returns a React.RefObject<T>. Attach it to any element to scope the listener to that element instead of window.

Key Combos & Modifiers

Combine modifier keys with + syntax:

Modifier AliasDescription
Ctrl / ControlControl key
ShiftShift key
Alt / Opt / OptionAlt / Option key
Meta / Cmd / CommandCommand (Mac) or Windows key
CtrlOrCmdCtrl on Windows/Linux, Cmd on macOS
AltOrCmdAlt on Windows/Linux, Cmd on macOS
spaceSpace bar