I have a general question about useEffect() vs setTimeout().
import { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => console.log(count)); // effect
const handleClick = () => {
setCount(count + 1);
setTimeout(() => console.log(count), 5000); // log to console after 5 seconds
}
return (
<>
<p>You clicked {count} times</p>
<button onClick={handleClick}>Click Me</button>
</>
);
}
export default Counter;
In the above code,
setCount(count + 1);
setTimeout(() => console.log(count), 5000);
using setTimeout(), I am trying to log count after 5 seconds, by which time setCount(), although asynchronous, would have definitely finished.
Then why does that still print the previous value of count, while useEffect() code prints the updated value? Can someone tell me what I am missing.