Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How stop setInterval automatically in React hooks?

I want build a Circular ProgressBar that count at 60 and then automatically stop.

But it can’t stop.

I want use React hooks and useEffect

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code here:

https://codesandbox.io/s/nostalgic-khorana-lijdyo?file=/src/App.js:0-686

But the code essence here also:

import React, { useState, useEffect } from "react";
import Circle from "./Circle";
export default function App() {
  const [counter, setCounter] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      if (counter < 60) {
        setCounter((t) => t + 1);
        console.log(counter);
      } else {
        console.log(`Why not run?`);
        return () => clearInterval(intervalId);
      }
      return () => clearInterval(intervalId);
    }, 100);
  }, []);

  return (
    <div>
      <div>
        <Circle
          size={250}
          strokeWidth={5}
          percentage={counter}
          color="#229880"
        />
      </div>
    </div>
  );
}

>Solution :

Here is my solution for this

 const [counter, setCounter] = useState(0);
  const counterValid = counter < 60;
  useEffect(() => {
    const intervalId = counterValid && setInterval(() => 
        setCounter((t) => t + 1)
      , 100);
      return () => clearInterval(intervalId)
  }, [counterValid]);

  return (
    <div>
      <div>
        <Circle
          size={250}
          strokeWidth={5}
          percentage={counter*(100/60)}
          color="#229880"
        />
      </div>
    </div>

We add counterValid as a dependency to useEffect to re-run the effect whenever the validity of the counter changes.

Also note that your circle expects a 1-100 value for percentage so I multiplied it by 100/60.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading