I wrote a program that adds or subtracts a unit to count
by pressing the up and down keys on the keyboard.
The problem is that the program does not work properly. When you press the key, look at the console, which runs several times, while each time you press the key, it only has to run once.
This is a problem that crashes after pressing the up or down buttons a few times, please help
import React, { useState } from "react";
export default function Example() {
const [count, setCount] = useState(0);
document.addEventListener("keydown", function (e) {
switch (e.keyCode) {
case 38:
setCount(count + 1);
console.log(count);
break;
case 40:
setCount(count - 1);
console.log(count);
break;
}
});
return (
<div>
<p>You clicked {count} times</p>
</div>
);
}