count down timer in react native
// isResendEnable is just my custom variable to check if i have enabled
// resend function in my otp box
const [timerCount, setTimer] = useState(20);
const [activator, setActivator] = useState(Math.random());
useEffect(() => {
let interval;
if (isResendEnable) {
interval = setInterval(() => {
if (timerCount > 0) {
setTimer(lastTimerCount => {
lastTimerCount <= 1 && clearInterval(interval);
return lastTimerCount - 1;
});
}
}, 1000);
}
return () => {
if (isResendEnable) {
clearInterval(interval);
}
};
}, [activator]);
return <Text> Resend in {timerCount} sec </Text>