I am new to react and have been trying to find an answer to this issue without much success. So, in this case, when I have all the function logic in the event listner's declaration it behaved weirdly ->
const [guess, setGuess] = useState<Array<String>>([]);
useEffect(() => {
window.addEventListener("keydown", ({ key }) => {
console.log(key);
if (guess.length < 5) {
const isChar = /^[a-zA-Z]$/.test(key);
if (isChar) {
setGuess((prev) => [...prev, key]);
}
}
});
return () => {
window.removeEventListener("keydown", ({ key }) => {
console.log(key);
if (guess.length < 5) {
const isChar = /^[a-zA-Z]$/.test(key);
if (isChar) {
setGuess((prev) => [...prev, key]);
}
}
});
};
}, [guess.length]);
The way it works is it adds a lot of characters to the guess array instead of adding just the one whereas when I put all the function logic into a function and pass is as a callback like as shown below, it works as intended (Mainly, my goal was to have an event listener which should add the keypresses into an array, I am making a clone of Wordle)
useEffect(() => {
function handleKeyDown({ key }: { key: string }) {
console.log(key);
if (guess.length < 5) {
const isChar = /^[a-zA-Z]$/.test(key);
if (isChar) {
setGuess((prev) => [...prev, key]);
}
}
}
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [guess.length]);
Any help is greatly appreciated!