I have a setState hook inside forEach loop that should update state after each 1000ms
useEffect(() => {
startTypingAnimation("From past to the future");
}, []);
function startTypingAnimation(sentence) {
let wordsArr = sentence.split("");
let animArr = [];
wordsArr.forEach((item, index) => {
setTimeout(() => {
animArr.push(item);
setAnimText(animArr);
console.log("animArr = ", animArr);
console.log("animText = ", animText);
}, 1000 * (index + 1));
});
}
To make typing effect here:
<Typography variant="h2" align="right">
{animText}
</Typography>
console.log(animArr) shows expectable behavior, but animText shows undefined in each loop.
Why am I getting this behavior?