Back to List
๐ฑ Verification Code Countdown Example
Implement SMS verification code countdown using useEffect + timer, demonstrating the importance of cleanup functions
๐ฏ Interactive Demo
๐ป Core Implementation
// โ
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';๐ Key Points
- Use setTimeout/setInterval for countdown
- Clear timers in cleanup function to prevent memory leaks
- Reset button state when countdown ends
- In real projects, call actual SMS API
- Add phone validation and anti-spam mechanisms
๐ Real-World Scenarios
- SMS verification during registration/login
- Phone verification for password reset
- Binding/unbinding phone numbers
- Secondary verification for sensitive operations (transfers)
- Email verification countdown (similar pattern)