ReactEasy

What is a controlled component?

A controlled component is a form element whose value is driven by React state: you pass value (or checked) from state and update that state in onChange. React is the single source of truth, so the input always shows exactly what the state says.

How it works

  1. State holds the value: const [email, setEmail] = useState("").
  2. The input reads it: value={email}.
  3. Every keystroke calls onChange, which updates state.
  4. React re-renders and the input shows the new state.

Benefits

  • Instant validation and formatting (uppercase, masks, max length).
  • Conditionally disable submit buttons or show errors as the user types.
  • Easy to reset or prefill from state.
  • One source of truth for multi-field logic.

Costs

  • A re-render on every keystroke. Usually fine, but huge forms can become slow. Libraries like React Hook Form use uncontrolled inputs for performance.
  • More boilerplate per field.

Rules

  • Provide onChange (or readOnly) whenever you pass value, otherwise React warns and the field is frozen.
  • Never switch an input between controlled and uncontrolled: avoid value={undefined} turning into a string. Initialize with "".
  • Checkboxes and radios use checked; <select> and <textarea> use value.

React 19 forms

With form Actions (<form action={fn}>), many forms do not need controlled inputs at all: read values from FormData on submit.

Code example

tsx
1import { useState } from "react";
2
3export function SignupForm() {
4 const [email, setEmail] = useState("");
5 const [agree, setAgree] = useState(false);
6 const [plan, setPlan] = useState("free");
7
8 const emailValid = /^\S+@\S+\.\S+$/.test(email);
9
10 return (
11 <form onSubmit={(e) => { e.preventDefault(); console.log({ email, agree, plan }); }}>
12 <input value={email} onChange={(e) => setEmail(e.target.value.trim())} placeholder="Email" />
13 {email && !emailValid && <p role="alert">Enter a valid email</p>}
14
15 <select value={plan} onChange={(e) => setPlan(e.target.value)}>
16 <option value="free">Free</option>
17 <option value="pro">Pro</option>
18 </select>
19
20 <label>
21 <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} /> I agree
22 </label>
23
24 <button disabled={!emailValid || !agree}>Sign up</button>
25 </form>
26 );
27}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app