I am experiencing a very weird bug in a basically fresh react project. I am attempting to update an array whenever the browser receives a keypress event. For some reason the update that I would expect to work is only editing the last value of the array or keeping it at a fixed length of 1.
function Component() {
const [keypresses, setKeypresses] = useState([]);
function updateKeypresses(e) {
setKeypresses([...keypresses, e.keyCode]);
}
useEffect(() => {
window.addEventListeneder('keydown', updateKeypresses);
return () => {
document.removeEventListener('keydown', updateKeypresses);
}
}, []);
useEffect(() => {
console.log(keypresses);
}, [keypresses])
}
Output: I dont have codes memorized so image nums
press a
~> [a]
press b
~> [b]
press c
~> [c]
What I would expect:
~> [a]
~> [a,b]
~> [a,b,c]
>Solution :
The reason that the keypresses array always reset it because your pointer of the updateKeypresses function isn’t changed.
to fix it you have to add the keypresses state to the dependecies array of useEffect:
useEffect(() => {
window.addEventListener('keydown', updateKeypresses);
return () => {
document.removeEventListener('keydown', updateKeypresses);
};
}, [keypresses]);