Implement SMS verification code countdown using useEffect + timer, demonstrating the importance of cleanup functions
// โ
Use constant: Ensure countdown starts from 60 seconds
const COUNTDOWN_DURATION = 60; // seconds
const [countdown, setCountdown] = useState(0);
// โ
Core countdown logic
useEffect(() => {
if (countdown > 0) {
const timer = setTimeout(() => {
setCountdown(countdown - 1);
}, 1000);
// ๐งน Cleanup function: Prevent memory leaks
return () => clearTimeout(timer);
}
}, [countdown]);
// Send verification code
const handleSendCode = async () => {
await api.post('/send-sms', { phone });
// โ
Use constant instead of hardcoding
setCountdown(COUNTDOWN_DURATION);
};
// Button text
const buttonText = countdown > 0
? `${countdown}s Retry`
: 'Send Code';