Why a simple useEffect
is not taking updated value when it is warping any setInterval/timeout inside;
where variable stopped to initial value;
import { useState, useEffect } from "react";
let timerRef;
const StopWatch = () => {
const [time, setTime] = useState(0);
const [isPause, setPause] = useState(false);
useEffect(() => {
timerRef = setInterval(() => {
console.log({ time });
if (!isPause) {
setTime(time + 1);
}
}, 5000);
return () => clearInterval(timerRef);
}, []);
const startWatch = () => {
setPause(false);
};
const stopWatch = () => {
setPause(true);
};
return (
<>
time: {time}
<button onClick={startWatch}>Start</button>
<button onClick={stopWatch}>stop</button>
</>
);
};
export { StopWatch };