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
- State holds the value:
const [email, setEmail] = useState(""). - The input reads it:
value={email}. - Every keystroke calls
onChange, which updates state. - 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(orreadOnly) whenever you passvalue, 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>usevalue.
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";23export function SignupForm() {4 const [email, setEmail] = useState("");5 const [agree, setAgree] = useState(false);6 const [plan, setPlan] = useState("free");78 const emailValid = /^\S+@\S+\.\S+$/.test(email);910 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>}1415 <select value={plan} onChange={(e) => setPlan(e.target.value)}>16 <option value="free">Free</option>17 <option value="pro">Pro</option>18 </select>1920 <label>21 <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} /> I agree22 </label>2324 <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.