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?
The problem is not setTimeout it's how you have used it. For example if you try executing below code:
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
Now this will only print "Hello" in the console once.
So, if you want the setTimeout to run only once do this:
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.