I think you just complicated the things unnecessarily, always remember this rule of thumb
whenever you want to update the state based on the previous state , pass a function to the setState() method, then react will make sure it will call the setState() with the latest value of the state variable.
This solution works, but it has a problem, the countdown never stops.
To make it stop at 0, we will make use of useRef hook, it will store the reference to the setInterval, whihc we can clear when the timer is 0.The complete solution would look like this.
hey this is a very nice implementation , but consider i want the timer to completely stop at 0 , and then we want the countdown again , if we change the value of timer then it won't do anything.
Any idea how we can overcome this
Hi Arpan , i think if you pass Timer as dependency in useEffect, that will do the job simply.
you dont need to use useRef and 2nd useEffect.
let me know your thoughts.
I think you just complicated the things unnecessarily, always remember this rule of thumb
This solution works, but it has a problem, the countdown never stops.
To make it stop at 0, we will make use of useRef hook, it will store the reference to the setInterval, whihc we can clear when the timer is 0.The complete solution would look like this.
codesandbox.io/s/reverent-bash-bxrnv
please let me know your thoughts on this.
Your solution is more intuitive than mine. Nice one!
Thank you!
hey this is a very nice implementation , but consider i want the timer to completely stop at 0 , and then we want the countdown again , if we change the value of timer then it won't do anything.
Any idea how we can overcome this
Hi Arpan , i think if you pass Timer as dependency in useEffect, that will do the job simply.
you dont need to use useRef and 2nd useEffect.
let me know your thoughts.
React.useEffect(() => {
const TimerInt = timer >0 && setInterval(() => {
setCounter((time)=>time-1);
}, 1000);
return () => {
clearInterval(TimerInt)
}
}, [timer]);