React timer
Fri Jan 03 2025 22:31:41 GMT+0000 (Coordinated Universal Time)
Saved by
@kanatov
const PomView = () => {
const [timer, setTimer] = useState(1500); // 25 minutes
const [start, setStart] = useState(false);
const firstStart = useRef(true);
const tick = useRef(); // <-- React ref
useEffect(() => {
if (firstStart.current) {
firstStart.current = !firstStart.current;
return;
}
if (start) {
tick.current = setInterval(() => {
setTimer((timer) => timer - 1);
}, 1000);
} else {
clearInterval(tick.current);
}
return () => clearInterval(tick.current);
}, [start]);
};
content_copyCOPY
Comments