Skip to content
Advertisement

ReactJS counter or timer with Start or Stop Button

Need help to understand in useEffect, if I don’t put counter and timerCheck in useEffect dependency then what it will effect here. And if I put timerCheck dependency in useEffect then counter increasing 100 time faster
Also how can i run this code without any error or warning
code in codesandbox

  const [counter, setCounter] = useState(0);
  const [startcounter, setStartcounter] = useState(false);
  const [timerCheck, setTimerCheck] = useState(0);

  useEffect(() => {
    let intervalStart = null;
    if (startcounter) {
      intervalStart = setInterval(() => {
        setCounter((prevState) => (prevState += 1));
      }, 1000);
      setTimerCheck(intervalStart);
    } else {
      clearInterval(timerCheck);
    }

    return () => {
      if (counter !== 0) clearInterval(timerCheck);
    };
  }, [startcounter]);

  const handleStartButton = () => {
    setStartcounter(true);
  };

  const handleStopButton = () => {
    setStartcounter(false);
  };

Advertisement

Answer

Try not to declare unnecessary states. timerCheck state is redundant.

  1. You want to start an interval that increases counter by one every second.
  2. When user stops the stopwatch , you want the interval to be cleared, so it would stop increasing the timer.

So your only dependancy in useEffect would be whether your stopwatch is running or not. And the only thing that matters to you, is when startCounter is ture. You start an interval when it is true and clear the interval in its cleanup.

  useEffect(() => {
    let intervalStart = null;

    if (!startcounter) {
      return () => {};
    }

    intervalStart = setInterval(() => {
      setCounter((prevState) => (prevState += 1));
    }, 1000);

    return () => {
      clearInterval(intervalStart);
    };
  }, [startcounter]);

Here is the codesandbox

But you do not really need useEffect for this. IMO it would be a much better code without using useEffect.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement