I am trying to log the latest value of state variable 'count'. The logging function is invoked by 'setInterval' function in useEffect hook. The state variable 'count' is updated by click of a button.
I am seeing the logged value as always zero, no matter how many times I click the button.
Why is this happening and how can it be fixed without using useRef? The code is also on codesandbox
export default function App() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount((count) => count + 1);
};
useEffect(() => {
let handle = setInterval(log, 5000);
return () => clearInterval(handle);
}, []);
const log = () => {
console.log(count);
};
return (
<div className="App">
<p>{count}</p>
<button onClick={() => handleClick()}>Add 1 </button>
</div>
);
}