Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
React useState entering infinite loop

I am using setInterval to increment the count and show it on a div like below. I am sure that the incrementcount is working nice. Dont know what mistake I am doing.

function DivClicker() {
 const [count, setCount] = React.useState<number>(0);

 function incrementCount():void{
    setCount((prev)=>prev+1);
 }
 setInterval(incrementCount,1000);

  return (
    <div>
        <div className='middle-div'>
            <div>{count}</div>
        </div>
    </div>
  )
}

export default DivClicker;

It is going crazy and incrementing hugely in matter of seconds.. Kindly guide. Mostly it is going in an infinite loop. I dont know why.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're not only setting state each render - causing an infinite loop, but you're adding a new interval that sets state each render. So each time you're adding more and more infinite setStates.

Fix this by setting your interval only once in a useEffect:

function DivClicker() {
 const [count, setCount] = React.useState<number>(0);

 function incrementCount():void{
    setCount((prev)=>prev+1);
 }
 
 useEffect(() => {
   const interval = setInterval(incrementCount,1000);

   return () => clearInterval(interval);
 }, []);

  return (
    <div>
        <div className='middle-div'>
            <div>{count}</div>
        </div>
    </div>
  )
}

export default DivClicker;

If you get an es-lint warning about a missing dependency, you can move incrementCount into the useEffect.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!