Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updated state value is not reflected inside setInterval() in React

I have the following:

const [isPaused, setIsPaused] = useState(false);
const myTimer = useRef(null);

const startTimer = () => {
  myTimer.current = setInterval(() => {
    console.log(isPaused); // always says "false"
  }, 1000);
};

Elsewhere in the code while this timer is running I'm updating the value of isPaused:

setIsPaused(true);

But this isn't reflected in the console log, it always logs false. Is there a fix to this?


1 Answers

The myTimer.current never changed which means isPaused is always false inside the function.

You need to make use of useEffect to update myTimer.current every time isPaused is updated.

useEffect(() => {
  function startTimer() {
    myTimer.current = setInterval(() => {
      console.log(isPaused);
    }, 1000);
  };
  
  startTimer();
  return () => clearInterval(myTimer.current); // cleanup
}, [isPaused]);
like image 179
Joseph D. Avatar answered Oct 17 '25 04:10

Joseph D.