'set interval not stopping after calling clearinterval() [duplicate]

im working on a tracking application that starts the set interval which gets the geolocation every 5 seconds after clicking the start button. the start button sets the tracking state to true which starts the set interval in the first place. I'm trying to stop the set interval when I click on the end button by setting the track state to false but the set interval keeps on going even if the track state turns to false

my component

        <button id="start" onClick={() => setTrackState(true)}>
           Start
        </button>
        <button id="end" onClick={() => setTrackState(false)}>
           End
        </button>

my hook

useEffect(() => {
  console.log("track useEffect");
  console.log(`trackState is ${trackState}`);
  if (trackState) {
     const interval = setInterval(() => {
        console.log("the interval is running");
        navigator.geolocation.getCurrentPosition(
           onSuccess,
           onError,
           options
        );
     }, 5000);
  } else {
     console.log("the interval is not running");
     clearInterval();
  }
}, [trackState, setTrackState]);


Solution 1:[1]

I could solve the problem by the following approach. I am new to react and I didn't know I had to clear the setInterval twice when using the setInterval function

useEffect(() => {
  let interval = null;
  console.log("track useEffect");
  console.log(`trackState is ${trackState}`);
  if (trackState) {
     interval = setInterval(() => {
        console.log("the interval is running");
        navigator.geolocation.getCurrentPosition(
           onSuccess,
           onError,
           options
        );
     }, 5000);
  } else {
     console.log("the interval is not running");
     clearInterval(interval);
  }
  return () => clearInterval(interval);
}, [trackState]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RusJ