0

I started a timer and want to stop it if the state of isPaying changes to false

  const [isPlaying, setIsPlaying] = useState(false)
  const isPlayingRef = useRef(isPlaying);

  const play = () => {
    setIsPlaying(true);
    const interval = setInterval(() => {
      if(!isPlaying){
        clearInterval(interval);
      }
      console.log('isPlaying ', isPlaying);
      console.log('isPlaying ', isPlayingRef.current);
    }, 5000);
  }

Both isPlaying and isPlayingRef.current are false inside the timer despite that I am setting the value to true in the play function.

user567
  • 3,712
  • 9
  • 47
  • 80
  • can' see any `isPlayingRef.current = true` in your `play` function :) – dbuchet May 18 '22 at 09:20
  • 1
    Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Giorgi Moniava May 18 '22 at 09:23
  • `isPlayingRef.current` will always be `false` since it is set only once, where `isPlaying` is `false` – Anurag Srivastava May 18 '22 at 09:33
  • I switched to the hook UseInterval which woks like a charm https://usehooks-ts.com/react-hook/use-interval – user567 May 18 '22 at 09:56

0 Answers0