I wanted to store 4 "hi" in an array. Instead of:
strArr.push('hi');
strArr.push('hi');
strArr.push('hi');
strArr.push('hi');
I did this:
for(let i = 0; i<4; i++){
setStrArr([...strArr, "hi"])
}
However, I get this error: Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
I couldn't figure out what was wrong and I was wondering if it didn't reach when i=3. So I did a check:
for(let i = 0; i<4; i++){
setStrArr([...strArr, "hi"])
if(i==3){
console.log("done")
}
}
The value of 'i' did reach 3, but why does my code run again?
This is my code:
function MyApp(){
const [strArr, setStrArr] = useState([]);
for(let i = 0; i<4; i++){
setStrArr([...strArr, "hi"])
if(i==3){
console.log("done")
}
}
return(
<div>
</div>
)
}