DEV Community

Discussion on: React Hooks Series: useRef

Collapse
 
jamesncox profile image
James Cox

Thank you for reading and the feedback, Joseph!

Funny that you mention using useEffect to also stop the timer, with a local variable, because I tried that several different ways, and couldn't get the timer to stop immediately on pressing pause. I am sure there is a better way, I just don't know what that is (yet)!

I think for me the issue is having the setTimeout inside the conditional block (start === true) and accessing that variable to clearTimeout isn't possible.

That's why useRef made a lot of sense to me. Accessible basically anywhere!

But I am open to new ideas and solutions! If there is a better way, I would love to know what that is!

Collapse
 
icyjoseph profile image
Joseph

Mmm perhaps I am missing something, did you try this?

useEffect(() => {
     let timer;
     if (start === true) {
        timer = counter > 0 && setTimeout(() => setCounter(counter - 1), 1000)
     }
     return () => {
        clearTimeout(timer)
      }
  }, [start, counter, setCounter])

And we could even get rid of counter:

useEffect(() => {
     let timer;
     if (start === true) {
        timer = setTimeout(() => setCounter(x => x === 0 ? 0 : x - 1), 1000)
     }
     return () => {
        clearTimeout(timer)
      }
  }, [start, setCounter])