I am trying to create a countdown timer but i hit something interesting...
This code procs twice in a row , as in the useEffect runs twice per second.
'use client'
import {useState, useEffect, useRef} from 'react'
export default function Home() {
const [timer, setTimer] = useState(null)
let intervalId = useRef(null)
const start=()=>{
setTimer(900)
intervalId.current = setInterval(()=>{
setTimer((timer)=>timer-1)
}, 1000)
}
useEffect(()=>{
if (timer < 1 && timer != null) {
setTimer(null)
clearInterval(intervalId.current);
console.log("proccccccccccccc")
}
}, [timer])
useEffect(()=>{
start()
}, [])
return (
<main className="">
{timer}
</main>
)
}
this procs once per second ( remove the condition && timer != null at useEffect )
'use client'
import {useState, useEffect, useRef} from 'react'
export default function Home() {
const [timer, setTimer] = useState(null)
let intervalId = useRef(null)
const start=()=>{
setTimer(900)
intervalId.current = setInterval(()=>{
setTimer((timer)=>timer-1)
}, 1000)
}
useEffect(()=>{
if (timer < 1) {
setTimer(null)
clearInterval(intervalId.current);
console.log("proccccccccccccc")
}
}, [timer])
useEffect(()=>{
start()
}, [])
return (
<main className="">
{timer}
</main>
)
}
I couldnt for the life of me understand why despite reading it many times over...