Lessons in this course (17)

4. Controlled vs uncontrolled forms

Basic★ Must knowLesson 4 of 17
jsx
// Controlled: React state is the source of truth
function LoginForm({ onLogin }) {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");
  function handleSubmit(e) {
    e.preventDefault();
    if (!email.includes("@")) return setError("Enter a valid email");
    onLogin(email);
  }
  return (
    <form onSubmit={handleSubmit}>
      <input type="email" value={email} onChange={e => setEmail(e.target.value)} />
      {error && <span role="alert">{error}</span>}
      <button>Login</button>
    </form>
  );
}

// Uncontrolled: the DOM holds the value; read it with a ref or FormData
function SearchForm() {
  const inputRef = useRef(null);
  return <form onSubmit={e => { e.preventDefault(); search(inputRef.current.value); }}><input ref={inputRef} defaultValue="" /></form>;
}

For real forms, React Hook Form (uncontrolled, performant) + Zod schema validation is common; React 19 adds form Actions (below).