I'm trying to build a simple count down timer using react hooks to count down 3 seconds. But after 3 seconds UI stop rendering but in console.log I can still is prints out every second. Why is the second array parameter in useEffect doesn't prevent this from happening?
function CounterGame() {
const [timeout, setTimeout] = React.useState(3);
React.useEffect(() => {
let id = window.setInterval(() => {
if (timeout > 0) {
setTimeout(x => x - 1 );
}
// this line keep executing even it timeout reach 0
console.log("in setInterval", timeout);
}, 1000)
return () => {
window.clearInterval(id);
}
}, [timeout])
return (
<div className="App">
See instructions.
<h1>{timeout} seconds</h1>
{!timeout && <button>Click</button>}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<CounterGame />, rootElement);