I have been experimenting with setInterval
. Both the codes were executed in Chrome. Below is my react component
function App() {
let [value, setValue] = useState(0);
useEffect(() => {
const id = setInterval(() => console.log(value), 1000);
return () => clearInterval(id);
}, []);
return (
<div className="App">
<p>{value}</p>
<button onClick={() => setValue(value + 1)}>+</button>
<button onClick={() => setValue(value - 1)}>-</button>
</div>
);
}
The console.log
in setTimeout
inside useEffect
keeps printing 0
no matter how many times you increment or decrement the value via button click.
Following code is being executed in browser (Chrome) console
let value = 0;
setInterval(() => console.log(value), 1000);
value = 3; // can be considered as setValue (sort of)
Now the browser console prints 3
which is expected.
I wonder why there is a difference in behaviour and would appreciate if someone could point out the reason for this. Any other code snippet or link that demonstrate this even better would be great.