Case 1:
const [present, setPresent] = useState([]);
useEffect(() => {
for (var j = 1; j <= totalPeriod; j++) {
setPresent([
...present,
{
period: j,
present: true,
},
]);
}
}, []);
Case 2:
const [present, setPresent] = useState([]);
let createPresent = [];
for (var j = 1; j <= totalPeriod; j++) {
createPresent = [
...createPresent,
{
period: j,
present: true,
},
]
}
useEffect(() => {
setPresent(createPresent);
}, []);
When I am trying to update the present state using loop in inside useEffect()
in Case 1, present state is not updating. But when I am separately using loop outside the useEffect()
and creating an array which I am then assigning to present state in case 2, the present state is getting updated.
What is the reason behind this? Why present state is not updating in Case 1?