react-use/docs/useKeyPressEvent.md
streamich c0658f605f feat: 🎸 refactor useKeyPressEvent hook
Changes its interface, fixes bug of calling callback on initial mount,
useKeyPress hook is injected as dependency and can be overwirtten to
useKeyboardJs.

BREAKING CHANGE: 🧨 useKeyPressEvent hook modified for dependency injection and providing
event objects to user
2019-03-28 19:28:19 +01:00

1.1 KiB

useKeyPressEvent

This hook fires keydown and keyup calllbacks, similar to how useKey hook does, but it only triggers each callback once per press cycle. For example, if you press and hold a key, it will fire keydown callback only once.

Usage

import React, { useState } from React;
import useKeyPressEvent from 'react-use/lib/useKeyPressEvent';

const Demo = () => {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count => ++count);
  const decrement = () => setCount(count => --count);
  const reset = () => setCount(count => 0);

  useKeyPressEvent(']', increment, increment);
  useKeyPressEvent('[', decrement, decrement);
  useKeyPressEvent('r', reset);

  return (
    <div>
      <p>
        Try pressing <code>[</code>, <code>]</code>, and <code>r</code> to
        see the count incremented and decremented.</p>
      <p>Count: {count}</p>
    </div>
  );
};

Reference

useKeyPressEvent('<key>', keydown);
useKeyPressEvent('<key>', keydown, keyup);
useKeyPressEvent('<key>', keydown, keyup, useKeyPress);