How to make setInterval() work in React?

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.

There’s a wonderful blog post by Dan Abramov (one of the core member of React) that uses timer to better explain Hooks, I suggest you to give it a read :slight_smile:

2 Likes

No, that won’t work. You’re going to need to use a ref here. Helpfully, there is a detailed guide on how to make it work

(edit: snap)

2 Likes

I tried using a class-based component instead of React Hooks and it seems to work as intended. I think I’ll stick with class-based for now since I haven’t studied Hooks quite well yet. Thanks for your answers. :slight_smile: