비트베이크

Implementing a Perfect SMS Verification Form & Timer with React Hook Form and Zod

2026-05-04T01:02:43.995Z

A professional and modern image depicting developer security with code elements, suitable for a tech blog post thumbnail with text overlay.

The Biggest Bottleneck in Signups: SMS Verification Forms

Where do you lose the most users during the signup process? Often, it's the 'Phone Verification' step. From a developer's perspective, building an SMS authentication form is surprisingly tricky. You have to handle phone number validation, OTP sending state, a 3-minute countdown timer, and timeout exceptions. If you try to manage all of this with basic React state (useState), your code can quickly turn into a spaghetti mess.

In this article, we'll explore how to escape the state management nightmare and build a flawless SMS verification form using React Hook Form (RHF), Zod, and a simple Custom Hook.


Solution Overview

By following this tutorial, you will build a robust component combining three key elements:

  1. Zod: For strict validation of phone numbers (Regex) and OTPs (6 digits).
  2. Custom Timer Hook: Encapsulating the setInterval logic for a 3-minute (180 seconds) countdown.
  3. React Hook Form: Managing form state cleanly without unnecessary re-renders.

Step-by-Step Implementation

1. Defining the Zod Schema

First, define the shape and validation rules of your form data. Zod makes it incredibly intuitive to handle complex regex validations.

import * as z from 'zod';

export const smsSchema = z.object({
  phone: z.string().regex(/^010\d{8}$/, "Please enter an 11-digit number starting with 010 (no dashes)."),
  code: z.string().length(6, "Please enter a 6-digit verification code.").optional(),
});

export type SmsFormValues = z.infer;

2. Creating a Custom Timer Hook (useTimer)

Keeping timer logic inside your component makes the code cluttered. Let's separate it into a custom hook named useTimer for better reusability.

import { useState, useEffect, useCallback } from 'react';

export const useTimer = (initialSeconds: number) => {
  const [timeLeft, setTimeLeft] = useState(initialSeconds);
  const [isActive, setIsActive] = useState(false);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (isActive && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft((prev) => prev - 1);
      }, 1000);
    } else if (timeLeft === 0) {
      setIsActive(false);
    }
    return () => clearInterval(interval);
  }, [isActive, timeLeft]);

  const start = useCallback(() => {
    setTimeLeft(initialSeconds);
    setIsActive(true);
  }, [initialSeconds]);

  const stop = useCallback(() => {
    setIsActive(false);
  }, []);

  const formatTime = () => {
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  };

  return { timeLeft, isActive, start, stop, formatTime };
};

3. Building the Complete Form Component

Now, let's assemble the UI using RHF and our custom hook. By using RHF's trigger method, we can validate the 'phone' field independently before submitting the entire form.

import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { smsSchema, SmsFormValues } from './schema';
import { useTimer } from './useTimer';

export const SmsVerificationForm = () => {
  const [isSent, setIsSent] = useState(false);
  const { timeLeft, isActive, start, formatTime, stop } = useTimer(180); // 3-minute timer

  const { register, handleSubmit, formState: { errors }, trigger, getValues } = useForm({
    resolver: zodResolver(smsSchema),
    mode: 'onChange',
  });

  // Handler for sending OTP
  const handleSendCode = async () => {
    const isPhoneValid = await trigger("phone");
    if (!isPhoneValid) return;

    const phone = getValues("phone");
    
    // TODO: Call backend API (POST /send)
    console.log(`Sending SMS to ${phone}`);
    
    setIsSent(true);
    start();
  };

  // Handler for final verification
  const onSubmit = async (data: SmsFormValues) => {
    if (!isActive && timeLeft === 0) {
      alert("Verification time has expired. Please request a new code.");
      return;
    }

    // TODO: Call backend API (POST /verify)
    console.log("Verifying code:", data.code);
    
    stop();
    alert("Verification successful!");
  };

  return (
    
      <div>
        Phone Number
        <div>
          
          
            {isSent ? "Resend" : "Send OTP"}
          
        </div>
        {errors.phone &amp;&amp; <p>{errors.phone.message}</p>}
      </div>

      {isSent &amp;&amp; (
        <div>
          Verification Code
          <div>
            
            <span>
              {formatTime()}
            </span>
          </div>
          {errors.code &amp;&amp; <p>{errors.code.message}</p>}
        </div>
      )}

      
        Verify
      
    
  );
};

💡 Tips & Best Practices

  • Auto Formatting: To improve UX, consider adding a transform layer to your Zod schema: z.string().transform(v =&gt; v.replace(/-/g, '')). This automatically strips dashes if users accidentally type them.
  • Handling Expiration: Notice how the submit button is disabled when timeLeft === 0. This is a best practice to prevent unnecessary API calls once the code has expired.

The Frontend is Perfect. What About the Backend API?

You've just built a flawless UI with top-tier state management. Now, all you need is an SMS API to actually deliver messages to your users' phones.

However, if you've looked into traditional SMS services, you've likely hit a wall. Most providers require business registration documents, proof of usage, and a lengthy approval process. For indie developers, freelancers, and startups trying to launch an MVP quickly, this is a massive hurdle.

That's where EasyAuth (이지어스), the ultra-simple SMS authentication API, comes in!

  • 🚫 No Paperwork: Start instantly upon signup—no business registration required.
  • 5-Minute Integration: Forget complex setups. Just two intuitive endpoints: POST /send and POST /verify.
  • 🤖 Automatic Sender ID: Skip the tedious sender number pre-registration process.
  • 💰 Highly Affordable: Only 15~25 KRW per message (up to 60% cheaper than traditional providers).
  • 🎁 Free Trial: Get 10 free test credits instantly upon signup.

EasyAuth Integration Example (Works with Next.js, Express, etc.)

// POST /send - Request OTP
await fetch('https://api.easyauth.co.kr/send', {
  method: 'POST',
  headers: { 'Authorization': 'Bearer YOUR_API_KEY' },
  body: JSON.stringify({ phone: data.phone })
});

Solve your frontend state management nightmare with React Hook Form, and skip the backend paperwork hell with EasyAuth. Sign up today, claim your 10 free credits, and get your SMS verification running in minutes!

비트베이크에서 광고를 시작해보세요

광고 문의하기

다른 글 보기

2026-08-06T06:01:33.120Z

2026 GTX 개통 임박! A/B/C 노선 수혜지역 투자 가이드

2026년 GTX A/B/C 노선 개통이 임박하며 수도권 부동산 시장이 들썩이고 있습니다. GTX 노선별 개통 현황과 함께, 주요 수혜지역을 심층 분석하고 실거주 및 투자를 위한 현명한 전략과 유의점을 제시하여 성공적인 아파트 투자를 돕는 가이드입니다.

2026-08-05T06:01:33.825Z

2026 하반기 재건축 투자: 규제 완화 속 핵심 전략

2026년 하반기, 규제 완화 기대감 속 재건축 투자의 핵심 전략을 알아봅니다. 정부 정책 변화 분석, 유망 지역 선정 기준, 주의할 점, 그리고 성공적인 투자를 위한 전문가들의 조언까지, 2026 부동산 시장에서 기회를 잡을 방법을 제시합니다.

2026-08-04T06:01:37.246Z

2026 하반기 청약, 대출 금리 변화 활용 내집마련 필승 전략

2026년 하반기 청약 시장은 변화하는 대출 금리와 정책, 지역별 수급 상황에 따라 기회와 도전이 공존합니다. 이 글에서는 부동산 시장 동향과 주택담보대출 전략, 인기 청약 단지 분석, 청약 가점 및 특별공급 활용 팁 등 내 집 마련을 위한 필승 전략을 제시합니다. 철저한 준비와 현명한 판단으로 2026년 내 집 마련의 꿈을 이루세요.

2026-08-04T01:01:36.795Z

2026년 청약 성공 전략: 무주택자 내집마련 필승 가이드

2026년 무주택자의 내집마련 꿈을 위한 필승 청약 전략 가이드입니다. 청약 가점부터 특별공급 활용법, 현명한 대출 전략, 유망 단지 분석, 그리고 제도 변화까지 2026년 청약 성공을 위한 모든 정보를 담았습니다.

서비스

피드자주 묻는 질문고객센터

문의

비트베이크

레임스튜디오 | 사업자 등록번호 : 542-40-01042

경기도 남양주시 와부읍 수례로 116번길 16, 4층 402-제이270호

트위터인스타그램네이버 블로그