I am building a simple timer app and keeping track of elapsed time in state using hooks. I know I am setting state correctly because it displays in the app every passing second. However, when I console log elapsedTime
, it repeatedly logs the initial state (0 in this case):
const Timer = () => {
const [elapsedTime, setElapsedTime] = React.useState(0);
const [totalTime, setTotalTime] = React.useState(0);
const handleStart = () => {
const startTime = Date.now();
setInterval(() => {
const et = Math.floor((Date.now() - startTime) / 1000);
setElapsedTime(et);
console.log(elapsedTime);
}, 1000);
};
const handleStop = () => {
clearInterval();
};
return (
<div className='container'>
<div className='timer'>
<div className='title'></div>
<div className='time'>{elapsedTime}</div>
<button onClick={handleStart}>Start</button>
<button onClick={handleStop}>Stop</button>
</div>
</div>
);
};
ReactDOM.render(<Timer />, document.getElementById("root"));
<div id="root"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
Why is my change in state not being reflected in the console.log
I call on line 9?