Reputation: 1
Output: incrementing the second value after 1 sec.................1....2...3....4 etc tell me why it's behaving like this i know another process to do that but why this process is not stopping the interval
const [seconds, setSeconds] = useState(0);
const [Flag,setFlag]= useState(0);
function inc() {
setSeconds(seconds=>seconds + 1);
setFlag(1);
}
useEffect(() => {
let interval = setInterval(inc, 1000);
if(Flag===1)
{
console.log("inside");
clearInterval(interval);
}
}, []);
Upvotes: 0
Views: 333
Reputation: 20431
Why it is not stopping is simple:
useEffect
callback runs only once (because empty dependency array makes it behave like componentDidMount
). When that is run Flag
is 0, so clearInterval
is not run.
Upvotes: 0
Reputation: 166
We should add Flag as the useEffect dependency, otherwise useEffect won't know the Flag is changed to 1.
We should store the setInterval timer to Ref variable
const timer = useRef();
const [seconds, setSeconds] = useState(0);
const [Flag, setFlag] = useState(0);
function inc() {
setSeconds((seconds) => seconds + 1);
setFlag(1);
}
useEffect(() => {
if (Flag === 1) {
if (timer.current) {
clearInterval(timer.current);
}
} else {
timer.current = setInterval(inc, 1000);
}
}, [Flag]);
Upvotes: 1