skip to Main Content

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…

2

Answers


  1. This might be because you are running your app in strict mode. Check if in index.js the React.StrictMode element is present. This will render everything twice to detect problems. Building the app for production (npm build) will have it working as expected. But you can also remove the strict mode element if you wish–it may not detect all problems anymore, but I usually remove it as it’s too much to compensate for.

    Login or Signup to reply.
  2. Are you running the server in development mode? If so, that is intended behavior and won’t affect production builds. If you really need to, you can remove it by disabling strict mode. You can do that by removing the <React.StrictMode> tags in your App.js file.

    Strict mode is used to find bugs in your app. It will re-run effects and renders to find bugs caused by impure rendering and identify faulty effect cleanup. I heavily recommend you continue using it unless you’re sure you have a reason not to.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search