Using the time in javascript code is not the same as using in React Native, due the lifecycles used by React Native, we need to store the instance of the timer in state variables so that we are able to access the timer instance to perform any operation such as clearing a timer, resetting it etc.

So first define a state variable:

const [timerState, setTimerState] = useState(null);

Then in the useEffect, initialise the timer along with it’s callback:

let timer = null;
useEffect(() => {
        timer = setTimeout(() => {
            console.log('The set time has elapsed');
          }, 45 * 1000);
          setTimerState(timer);
      
          return () => {
            clearTimeout(timer);
          }
    }, []);

Notice that we use a local variable to initialise and store the timer instance. Also note that we are providing a second argument as an empty array in the useEffect hook. This is done so that the useEffect hook is called only when mounting and unmounting(unmounting calls the return method of the useEffect hook). This return method of the useEffect hook allows us to perform cleanup operations. In our case, the return method clears the timer out, ensuring that the timer is cleared when the component is unmounted.

This will start our timer and will elapse after the said interval(45ms * 1000 = 45 seconds).

Now, say we want to clear the timer when a button is clicked. We have a button’s onPress handler like the following:

function onButtonPress() {
        clearTimeout(timerState);
    }

Notice that we are using the timerState state variable when calling the clearTimeout method. If we had used the simple variable defined as let timer; in the clearTimeout method, the timer would not have been stopped because such variables don’t maintain their state during React Native lifecycle methods, thus we need the state variables.

Here is the complete code:

const TimerExampleComponent = () => {
    const [timerState, setTimerState] = useState(null);
    
    let timer = null;
    useEffect(() => {
        timer = setTimeout(() => {
            console.log('The set time has elapsed');
          }, 45 * 1000);
          setTimerState(timer);
      
          return () => {
            clearTimeout(timer);
          }
    }, []);

    function onButtonPress() {
        clearTimeout(timerState);
    }

    return(
        <Button
          title="Stop Timer"
          onPress={onButtonPress}
        />
    );
};
export default TimerExampleComponent;

Conclusion:

This post addresses a problem that many face when trying to get the instance of a timer in React Native to perform some operation. This cannot be done on a normal JavaScript global variable in React Native, but instead we need to use a state variable.