I want to increase the state [second] = [second + 1] after every second.
const [second,setSecond] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSecond(second+1)
}, 1000);
return () => clearInterval(interval);
}, []);
But it seems that an infinity loop occurs, the [second] just increases once, from 0 to 1, and it stops running.
I changed my code from
setSecond(second+1)
to
setSecond((second) => {return second+1})
And this one runs without problem:
const [second,setSecond] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSecond((second) => {return second+1})
}, 1000);
return () => clearInterval(interval);
}, []);
Seriously, I still don't get it clearly. Can anybody explain to me why? Thanks in advance!