I was trying to learn the intercepting routes in NextJs but i got this problem and i am using Nextjs 13.5.4.

This is the code for counter

'use client'
import {useState}from 'react'

export default function CounterNumber(){

  const [state, setState] = useState(0)
   
  setInterval(()=>{setState(state + 1)}, 1000)
   
  return (
     <h1>
        Count Value {state}
     </h1>
   )
}

This is the code for page.js

import CounterNumber from "../@componenets/Counter"

function Page() {
   
return (
   <div>
      <CounterNumber />
    </div>
   )
}

export default Page
1

There are 1 answers

2
Christian Ivicevic On

Chances are high that you are leaking due to running multiple intervals. You need to clean up intervals when unmounting which is particularly relevant when using React in Strict mode where components are mounted twice to check how robust they are. Try the following clean solution to dealing with the interval:

'use client'

import { useEffect, useState } from 'react'

export default function CounterNumber() {
  const [state, setState] = useState(0)

  useEffect(() => {
    let interval = setInterval(() => { setState(value => value + 1) }, 1000)

    return () => {
      clearInterval(interval)
    }
  }, [])
   
  return <h1>Count Value {state}</h1>
}