Forms are where most apps collect input, and React's model — state is the single source of truth — is worth getting right. This chapter goes beyond Chapter 4's intro to managing many fields, validating, submitting, and knowing when a form library earns its keep.
Controlled inputs
A controlled input's value comes from state and onChange writes back to it — so the value is always available in your code:
const [email, setEmail] = useState("");<input value={email} onChange={e => setEmail(e.target.value)} type="email" />
One handler, many fields
Store the whole form in one state object and use the input's name to update the right field:
const [form, setForm] = useState({ name: "", email: "", programme: "" });const handleChange = (e) => {const { name, value } = e.target;setForm(prev => ({ ...prev, [name]: value })); // spread + computed key};<input name="name" value={form.name} onChange={handleChange} /><input name="email" value={form.email} onChange={handleChange} />
Submitting
const handleSubmit = async (e) => {e.preventDefault(); // stop the page reloadawait fetch("/api/enquiry", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(form),});};<form onSubmit={handleSubmit}> … <button>Send</button> </form>
Validation
const [errors, setErrors] = useState({});const validate = () => {const e = {};if (!form.email.includes("@")) e.email = "Enter a valid email";if (form.name.length < 2) e.name = "Name is too short";setErrors(e);return Object.keys(e).length === 0; // true if no errors};{errors.email && <p className="error">{errors.email}</p>}
When to use a library
Hand-rolled state is fine for small forms. For large forms with complex validation, a library like React Hook Form removes boilerplate and improves performance (it minimises re-renders). Reach for one when the manual approach starts to hurt — not before.
Practice
Build a "Book a call" form with four fields in a single state object updated by one handleChange. Add a validate that populates an errors object and shows messages, and an onSubmit that only posts when valid.
Key takeaways
- 01Controlled inputs bind value to state and write back on onChange — state is the source of truth.
- 02Store many fields in one object; update with { ...prev, [name]: value } using the input's name.
- 03On submit, call e.preventDefault() then send the form state.
- 04Keep validation errors in state and render messages conditionally.
- 05Hand-roll small forms; reach for React Hook Form when complexity/performance demands it.
