Search code examples
reactjsreact-nativereact-hooksuse-stateclearinterval

How to clearInterval correctly using React Native


In RN, I have a countdown timer using setInterval that goes from 10 - 0. Once the condition is met of the time === 0 or less than 1, I want the interval to stop. The countdown is working but is repeating continuously, clearInterval not working. What am I doing wrong?

import { StyleSheet, Text } from 'react-native'
import React, {useEffect, useState} from 'react'


export default function Timer() {
  const [time, setTime] = useState(10)

  useEffect(() => {
    if(time > 0) {
      var intervalID = setInterval(() => {
        setTime(time => time > 0 ? time - 1 : time = 10)
      }, 1000)
    } else {
      clearInterval(intervalID)
    } 
    }, [])  


  return <Text style={styles.timer}>{time}</Text>
}

Solution

  • ClearInterval should be inside, setTime because useEffect will only trigger once.

    NOTE: you should also clear on unmount.

    export default function Timer() {
      const [time, setTime] = useState(10);
    
      useEffect(() => {
        var intervalID = setInterval(() => {
          setTime((time) => {
            if (time > 0) {
              return time - 1;
            }
            clearInterval(intervalID);
            return time;
          });
        }, 1000);
    
        return () => clearInterval(intervalID);
      }, []);
    
      return <Text style={styles.timer}>{time}</Text>;
    }