Form Submission: Event Handler, Not Effect
What you'll learn: Why form validation and submission logic belongs in onSubmit handlers, not in effects that watch form state.
The Core Idea
When a user clicks "Submit," that's an event — a specific action at a specific moment in time. Your code should respond directly to that event, not by watching form fields change and trying to guess when submission "should" happen.
The antipattern looks like this: watching form state with useEffect, then detecting some condition (like "all fields are filled") and auto-submitting. This creates confusing behavior and violates the principle that effects synchronize with external systems, not respond to user actions.
The Right Pattern
Handle submission exactly when the user triggers it:
function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
function handleSubmit(e) {
e.preventDefault();
// Validate here
if (!email || !password) {
alert('Please fill all fields');
return;
}
// Submit here
fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});
}
return (
<form onSubmit={handleSubmit}>
<input value={email} onChange={e => setEmail(e.target.value)} />
<input value={password} onChange={e => setPassword(e.target.value)} />
<button type="submit">Log In</button>
</form>
);
}
Validation logic, API calls, and state resets all belong in handleSubmit — not in a useEffect watching email and password.
Why This Matters
Event handlers run because the user did something. Effects run because state changed. Form submission is user-driven, so it belongs in an event handler.
Key Takeaway: Form submission is a user event, not a synchronization side effect — handle it in onSubmit, not useEffect.