Forms in React
Controlled and uncontrolled inputs, form validation, and handling form submission.
What you'll learn
- Controlled components and two-way data binding
- Handling multiple inputs with a single state object
- Form validation patterns and error display
- The difference between controlled and uncontrolled inputs
Concept
Controlled Components
In React, a controlled component is an input whose value is controlled by React state. The input's value is set from state, and every keystroke updates the state via onChange. This creates a single source of truth — the state drives the input, and the input updates the state. This circular flow gives you full control: you can validate, transform, or block input on every keystroke. Controlled inputs are the recommended pattern in React.
Handling Multiple Inputs
When a form has many fields, creating a separate state variable for each is tedious. Instead, use a single state object and a shared change handler that updates the field by name. Use the input's name attribute to identify which field changed: setForm(prev => ({ ...prev, [e.target.name]: e.target.value })). This computed property name pattern keeps your handler DRY regardless of how many fields the form has.
Form Validation
Validation can happen on every change (real-time) or on submit. For real-time validation, check the field value in the onChange handler or in a derived variable. Store errors in a separate state object and display them next to the relevant fields. For submit-time validation, validate all fields in the onSubmit handler before proceeding. Libraries like react-hook-form and zod can simplify complex validation, but for simple forms, manual validation is sufficient.
Uncontrolled Inputs
An uncontrolled input manages its own state in the DOM, and you read its value via a ref when needed (e.g., on submit). This is closer to traditional HTML form behavior. Uncontrolled inputs are simpler for one-time reads but harder to validate in real time. Use them for simple forms or when integrating with non-React code. For most cases, controlled inputs are preferred because they give you full control over the data flow.
Form Libraries
For complex forms with many fields, nested validation, or dynamic field arrays, consider a form library. react-hook-form is performant and minimizes re-renders. Formik is a popular, well-documented alternative. Pair them with a validation schema library like zod or yup for declarative validation rules. These tools handle the boilerplate of field registration, validation, error messaging, and submission so you can focus on the form logic.
Example
import { useState } from "react";
function RegistrationForm() {
const [form, setForm] = useState({ username: "", email: "", password: "" });
const [errors, setErrors] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setForm(prev => ({ ...prev, [name]: value }));
};
const validate = () => {
const errs = {};
if (!form.username) errs.username = "Username is required";
if (!form.email.includes("@")) errs.email = "Valid email required";
if (form.password.length < 8) errs.password = "Min 8 characters";
return errs;
};
const handleSubmit = (e) => {
e.preventDefault();
const errs = validate();
setErrors(errs);
if (Object.keys(errs).length === 0) {
console.log("Submitting:", form);
}
};
return (
<form onSubmit={handleSubmit}>
<input name="username" value={form.username} onChange={handleChange} />
{errors.username && <span className="error">{errors.username}</span>}
<input name="email" value={form.email} onChange={handleChange} />
{errors.email && <span className="error">{errors.email}</span>}
<input name="password" type="password" value={form.password} onChange={handleChange} />
{errors.password && <span className="error">{errors.password}</span>}
<button type="submit">Register</button>
</form>
);
}
A single state object holds all fields. The shared handleChange uses computed property names. Validation runs on submit and errors display inline.
Try it
- Regex Tester
Build and test regex patterns for email, password, and phone validation.
- JSON Formatter
Inspect form data as JSON before sending it to an API.
Common mistakes
The mistake
Forgetting to set the value prop on controlled inputs
The fix
A controlled input must have both value={state} and onChange={handler}. Without value, the input is uncontrolled and React cannot control it. Without onChange, the input becomes read-only.
The mistake
Creating separate useState calls for every form field
The fix
Use one state object and a shared handler with computed property names: setForm(prev => ({ ...prev, [name]: value })). This scales to any number of fields.
Practice Forms in React
6 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.