I know this code will work and the count value will be updated after every 2 seconds:
import React from 'react';
function App() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
setInterval(() => {
setCount(prev => prev + 1);
}, 2000);
}, []);
return <h1>{count}</h1>;
}
I am trying to understand why the below code doesn't work:
React.useEffect(() => {
const interval = setInterval(() => {
setCount(count + 1);
console.log('hello');
}, 2000);
return () => clearInterval(interval);
}, []);
In this case, count stays at 1 but the setInterval is called after every 2 seconds because hello is being logged every 2 seconds.
How
setIntervalis being called when component is not being rendered? Does it operate outside of React lifecycle or something?When I pass callback to
setCount(prev => prev + 1), then it works fine? Why? How theprevin callback getting the updated value?
I have read similar answers but still it is not making sense to me so if someone could please clear the doubt.
Thanks