Skip to content

Instantly share code, notes, and snippets.

@rickyansari
Last active December 6, 2022 20:42
Show Gist options
  • Save rickyansari/75782ce76d1e35cb4cebd91264c9812f to your computer and use it in GitHub Desktop.
Save rickyansari/75782ce76d1e35cb4cebd91264c9812f to your computer and use it in GitHub Desktop.
Count Down Timer hook. which can be used in react-native and react application.
import React, {useEffect, useState} from 'react';
const ON = 'on';
const OFF = 'off';
const defaultTimerValue = 3;
const defaultTimerInterval= 1000;
const defaultTimeOutCallback = ()=>{alert('Time Over)};
function useCountDownTimer({
initialValue = defaultTimerValue,
interval = defaultTimerInterval,
onTimeOut = defaultTimeOutCallback
} = {}) {
const [timer, setTimer] = useState(initialValue);
const [timerStatus, setTimerStatus] = useState(OFF);
const [intervalID, setIntervalID] = useState('');
useEffect(() => {
if (timer === 0) {
if (intervalID) {
clearInterval(intervalID);
onTimeOut();
}
setTimerStatus(OFF);
return;
}
if (timerStatus === OFF) {
const timerID = setInterval(
() => setTimer((currentTime) => currentTime - 1),
interval,
);
setIntervalID(timerID);
setTimerStatus(ON);
}
() => {
clearInterval(intervalID);
};
}, [timer, interval, intervalID, timerStatus, onTimeOut]);
function resetTimer() {
setTimer(initialValue);
}
return {timer, setTimer, resetTimer};
}
// Example Code for using the above hook
import React, {useEffect, useState} from 'react';
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
const App= () => {
const {timer, resetTimer, ...rest} = useCountDownTimer({initialValue: 10});
return (
<View style={styles.body}>
<Text>{timer}</Text>
<TouchableOpacity
onPress={() => {
resetTimer();
}}>
<Text>Reset</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
body: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'yellow',
},
})
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment