Use Setinterval In React
I'm trying to use setInterval in React but stuck on something I don't properly understand. The code is: const Countdown = () => { const [countdownSecond, setCountdownSecond]
Solution 1:
You can do:
const Countdown = () => {
const [countdownSecond, setCountdownSecond] = React.useState(0);
const [start, setStart] = React.useState(false);
React.useEffect(()=>{
const interval = null
if (start) {
interval = setInterval(()=>{
setCountdownSecond(countdownSecond + 1);
}, 1000);
}
return ()=>{if (interval !== null) clearInterval(interval)};
},[start]);
function x(e) {
e.preventDefault();
console.log(countdownSecond);
setStart(!start);
}
return (
<>
<button onClick={(e) => x(e)}>{start?"Stop":"Start"}</button>
<p>Countdown: {countdownSecond}</p>
</>
);
}
Post a Comment for "Use Setinterval In React"