Home > Software design >  React useState entering infinite loop
React useState entering infinite loop

Time:02-25

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.

CodePudding user response:

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.

  • Related