DEV Community

Yukiya Nakagawa
Yukiya Nakagawa

Posted on

Handle keyboard event with React Hooks

Sometimes you want to implement keyboard shortcuts. This is a sample for React Hooks.

useEffect(() => {
  // handler object
  const handleEvent = (ev: KeyboardEvent) => {
    console.log(`your key is ${ev.code}!`);
  };

  // register handler
  // do not use lambda here because to unsubscribe later
  window.addEventListener('keyup', handleEvent);

  // unregister handler
  return () => {
    window.removeEventListener('keyup', handleEvent);
  };
}, [/* any deps */]);

Then, handleEvent handles your keyevent.

Top comments (4)

Collapse
 
landgod profile image
Dan Gold

What is the purpose of removing the listener in the return statement?

Collapse
 
ac37s profile image
e1cb4 ac37s • Edited

Simple example: on one route u have 1 component with hook specified above. U change route. Then go back. What will happen on specified keydown? Assume SPA with react router. This is simple example. There are tons more complicated ones. It's even that case when we have no deps and adding event on mount, useEffect is MUCH more flexible.

Collapse
 
dance2die profile image
Sung M. Kim

As the event handler is bound to the window, even after the component is unmounted, the handler is still active.

As a general rule, cleaning up when unused would save memory and other possible issues.

Collapse
 
nkzn profile image
Yukiya Nakagawa • Edited

Sung and e1cb4's answer has explained all my opinion πŸ‘

these are purpose:

  • avoiding memory leak
  • each component should clean up each its own event handling

the function at return statement is called when the component is unmounted, so event handler is keeped active during the component is being mounted.