Bill
Bill

Reputation: 5150

React useEffect and clearInterval

I have a button that toggles the state named start from true to false. if true U want to see the console log, as soon as I press stop I want the log to stop.


  useEffect(() => {
    let timePassed = 0;
    let timeLeft = timeLimit;
    if (start) {
      const timerInterval = setInterval(() => {
        timePassed += 1;
        if (!start) {
          console.log('stop')
          clearInterval(timerInterval);
        }
        console.log('start')
      }, 100);
    }
  }, [start]);

The console never stop logging start

Upvotes: 1

Views: 58

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84912

The local variable start is never going to change, even if you call setStart. Calling setStart is just an instruction to react to render the component again. On that new render a new local variable will be created with start equal to false, but the effect from the previous render is never going to see that.

Instead, what you need is to return a teardown function. When the effect is called for a second time, react will call the previous time's teardown function.

useEffect(() => {
  let timePassed = 0;
  let timeLeft = timeLimit;
  if (start) {
    const timerInterval = setInterval(() => {
      timePassed += 1;
      console.log('start')
    }, 100);

    return () => {
      console.log('stop')
      clearInterval(timerInterval);
    }
  }
}, [start])

Upvotes: 1

Related Questions