So I’m trying to start the Pomodoro Clock project, but I’m having a bit of a problem. I’m trying to make a simple countdown timer just to test first how setInterval()
behaves in React but I can’t get it to work properly. This is the code I’m trying to run:
function App() {
const [seconds, setSeconds] = React.useState(10);
const startTimer = () => {
setInterval(decrement, 1000);
}
const decrement = () => {
setSeconds(seconds - 1);
console.log(seconds);
}
return (
<div>
<h1>{seconds}</h1>
<button onClick={startTimer}>START</button>
</div>
)
}
I’m basically trying to count down from 10 but I can’t get the state to change with setInterval()
. I tried to put a console.log in my decrement()
function to see how it behaves but it only displays the number 10 every 1 second, when it should be counting down from 10 every second. How do I get that to work in React?
Here’s a Codepen link to test it out.