C
React/State/Lesson 08

Form Handling

30 min·theory
This chapter
2/2
JavaScript

Form Handling

💡 Why Learn This?

🎯 It is essential for building input fields found on every website, including login, sign-up, and search forms.
💼 You can validate user input in real time and display errors immediately.
It is a foundational technique for verifying that form data is correct before sending it to the server.
🏢 실무에서는
In production, this pattern is used to show real-time feedback such as 'Minimum 8 characters required' when a user types a password in a sign-up form, or to send the input value to the server when the user clicks an email duplicate-check button. Checkout forms on e-commerce sites are also built using this same pattern.

Form Handling Patterns

React Form Handling

Controlled vs Uncontrolled Components

ApproachCharacteristicsUse Case
ControlledReact manages the valueReal-time validation
UncontrolledDOM manages the valueSimple forms
React 19 ActionsIntegrated with server actionsNext.js App Router

2025 Form Libraries

  • React Hook Form: Performance-optimized, uncontrolled-based
  • Zod: Schema-based validation
  • React 19 Actions: Built-in form handling
💻 Form Handling Practice
import { useState, useActionState } from "react";

// 1. Controlled Component
function LoginForm() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validate = () => {
    const errs: Record<string, string> = {};
    if (!email.includes("@")) errs.email = "Please enter a valid email";
    if (password.length < 8) errs.password = "Please enter at least 8 characters";
    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (validate()) {
      console.log("Login:", { email, password });
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <input type="email" value={email} onChange={e => setEmail(e.target.value)}
          className={`border rounded px-3 py-2 w-full ${errors.email ? "border-red-500" : ""}`}
          placeholder="Email" />
        {errors.email && <p className="text-red-500 text-sm">{errors.email}</p>}
      </div>
      <div>
        <input type="password" value={password} onChange={e => setPassword(e.target.value)}
          className="border rounded px-3 py-2 w-full" placeholder="Password" />
        {errors.password && <p className="text-red-500 text-sm">{errors.password}</p>}
      </div>
      <button type="submit" className="bg-blue-500 text-white px-4 py-2 rounded w-full">
        Login
      </button>
    </form>
  );
}

// 2. React 19 Actions (Next.js)
async function submitForm(prevState: any, formData: FormData) {
  const email = formData.get("email") as string;
  const password = formData.get("password") as string;
  if (!email.includes("@")) return { error: "Please enter a valid email" };
  // API call
  return { success: true };
}

function ActionForm() {
  const [state, action, isPending] = useActionState(submitForm, null);
  return (
    <form action={action}>
      <input name="email" type="email" />
      <input name="password" type="password" />
      <button disabled={isPending}>{isPending ? "Processing..." : "Submit"}</button>
      {state?.error && <p className="text-red-500">{state.error}</p>}
    </form>
  );
}

💡 💡 Form Handling Tips

  • Simple forms: useState + manual validation
  • Complex forms: React Hook Form + Zod
  • Next.js: Server Actions + useActionState
  • React 19: <form action={fn}> pattern is now standardized

This concept is central to React component development. Understand React's declarative UI paradigm and clearly distinguish the difference between props and state. A component should behave like a pure function — always returning the same output (JSX) for the same input (props).

⚛️ React Pattern — Form Handling

Learn step by step, with code examples, how form handling is used in React.
1 🧩 1. When to Use Form Handling
Situations where this feature is needed.
2 💻 2. Writing the Code
Basic usage of form handling.
3 🎨 3. Rendered Output
What the user sees on screen.
4 💡 4. Practical Tips
Common pitfalls and best practices.

📝 Form — Controlled Component

Edits you make to the code are reflected automatically after 0.7 seconds. Runs instantly in the browser via React 18 + Babel.
🖥️ Result — rendered React component
✏️ React 코드 수정하기 (클릭해서 열기)
⚛️ React 18 + Babel Standalone — see the result first, then edit the code yourself.

Check Your Understanding

What is a Controlled Component?
💡 A controlled component manages the input's value through state. React takes full control of the input value via the onChange -> setState -> value flow. An uncontrolled component reads the value directly from the DOM using a ref.
Read this first: useState
Up next: useEffect
Form Handling - React