Skip to content

Instantly share code, notes, and snippets.

@lenivene
Created March 8, 2024 14:32
Show Gist options
  • Save lenivene/507139301b0f6477538499b866d90ea6 to your computer and use it in GitHub Desktop.
Save lenivene/507139301b0f6477538499b866d90ea6 to your computer and use it in GitHub Desktop.
This function, named `useResentCodeTimer`, is a custom React hook that manages a countdown timer for a resend code functionality
import { useState, useEffect } from 'react';
interface ResentCodeTimerProps {
initialValue?: number;
}
export const useResentCodeTimer = ({ initialValue = 60 }: ResentCodeTimerProps) => {
const [resentCodeIn, setResentCodeIn] = useState(initialValue);
let startTime: Date | undefined;
useEffect(() => {
if (resentCodeIn > 0) {
startTime = new Date();
} else {
startTime = undefined;
}
const intervalId = setInterval(() => {
if (startTime) {
const elapsed = Math.floor((new Date() - startTime) / 1000);
setResentCodeIn(Math.max(initialValue - elapsed, 0));
if (elapsed >= initialValue) {
clearInterval(intervalId);
}
}
}, 100);
return () => {
clearInterval(intervalId);
};
}, [resentCodeIn, initialValue]);
return resentCodeIn;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment