skip to Main Content

I have 2 hotkeys in my app, 1 and 2. If I press 1 release and then 2, it’s fine. But if I press both at the same time, it doesn’t increment as expected when I release both at the same time.

My expectation is that if I press 1 and 2, and then release both, I should have both incrementing by 1. But it doesn’t. I checked the API and tried some different options but it always seems to increment 2 in one of the cases.

import { useHotkeys } from 'react-hotkeys-hook';

export default function App() {
  const [cnt1, set1] = React.useState(0);
  const [cnt2, set2] = React.useState(0);

  useHotkeys('1', () => set1((v) => v + 1), { keyup: true });
  useHotkeys('2', () => set2((v) => v + 1), { keyup: true });

  return (
    <div>
      <div>{cnt1}</div>
      <div>{cnt2}</div>
    </div>
  );
}

A running example:

https://stackblitz.com/edit/stackblitz-starters-6mbnsa?file=src%2FApp.tsx

2

Answers


  1. Chosen as BEST ANSWER

    I think I made a mistake copying @0stone0 answer and inadvertently made it work. I'm still confused how this is working, but it even works if I have 4 numbers.

    Notice it only increments if the key I'm letting go up is not pressed.

      useHotkeys(
        '1',
        () => {
          if (!isHotkeyPressed('1')) {
            set1((v) => v + 1);
          }
        },
        {
          keyup: true,
        }
      );
      useHotkeys(
        '2',
        () => {
          if (!isHotkeyPressed('2')) {
            set2((v) => v + 1);
          }
        },
        {
          keyup: true,
        }
      );
    

  2. I’ve tried quite some ways to prevent this, found a single, not so great solution I thought I’d share.


    There seems to be a isHotkeyPressed hook that can be used in the second callback to check if the other hotkey is active:

    useHotkeys('2', () => {
        if (!isHotkeyPressed('1')) {
            set2((v) => v + 1);
        }
    }, { keyup: true });
    

    You could combine both hotkeys hooks into a single one (you can pass multiple keys comma separated) to make the isHotkeyPressed on the other key more dynamic.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search