Lab Projects
PythonReact/Next.jsBlogAbout

๐Ÿ“ฑ 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)