how seTimeout() executing continuously?

73 Views Asked by At

Since we know that setTimeout() function execute only once then how the following program executing continuously:

import {useState} from "react"

const App = () => {

        const [counter, setcounter] = useState(0);

        setTimeout( () => setcounter (counter+1), 1000)
        

        return (
          <div>{counter} </div>
        )

}

export default App

please anybody can identify it? which code piece triggering the setTimeout() to execute continuously?

1

There are 1 best solutions below

0
Singh Jatin On

The problem is not setTimeout it's how you have used it. For example if you try executing below code:

import { useState } from "react";

const App = () => {
  const [counter, setcounter] = useState(0);

  console.log("Hello");
  setTimeout(() => setcounter(counter + 1), 1000);

  return <div>{counter}</div>;
};

export default App;

The above code will print "Hello" continously. This is because in setTimeout you are changing the counter state which is making the App component to re-render. If you wrote this instead

const App = () => {
  const [counter, setcounter] = useState(0);
  
  setTimeout(() => console.log("Print"));

  return <div>{counter}</div>;
};

Now this will only print "Hello" in the console once.

So, if you want the setTimeout to run only once do this:

const App = () => {
  const [counter, setcounter] = useState(0);

  useEffect(() => {
    setTimeout(() => setcounter(counter + 1), 1000);
  }, []);

  return <div>{counter}</div>;
};

Now the useEffect also re-render your App component but it only does this for when the page loads as I have not passed any dependencies in the useEffect. But if you pass counter as the dependency in useEffect you will again have the same issue so try avoiding that.