Skip to content
Advertisement

Facing issue while updating auto increment counter value in react.js using useEffect Hook

I’m having an issue with the auto-increment counter, which updates every 2 secs. It updates the value but in a glitchy way Please check the code and share your views regarding the problem.

 const [counter, setCounter] = useState(1200)
 function handleCounter() {
    setCounter(counter + 1)
}
useEffect(() => {
    if (counter => 1200 && counter < 1364) {
        setInterval(handleCounter, 2000);
    }else {
        clearInterval(setInterval(handleCounter, 2000))
    }
    clearInterval(setInterval(handleCounter, 2000))
}, [counter])

Advertisement

Answer

try this

useEffect(() => {
    const timeInterval = setInterval(() => {
      counter < 1364 && setCounter((prevCount) => prevCount + 1);
    }, 2000);

    return () => {
      clearInterval(timeInterval);
    };
  }, [counter]);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement