DEV Community

Discussion on: React Hooks Series: useRef

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])