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
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.
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: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.