Sub topic 7
Controlled Inputs: The Parent Owns the Value
In the previous chapters, you moved shared state into a common parent and passed it down as props. This chapter looks at the most common case of that pattern, the form input. A controlled input is an input whose displayed value comes from props, and whose changes are reported upward through a callback.
This chapter assumes you know useState, how onChange events work in React, and how to pass props and callbacks between components.
What "controlled" means
A native <input> keeps its own value inside the browser's DOM. If you type "abc", the DOM node holds "abc", and React does not need to know. React calls this an uncontrolled input.
A controlled input hands that responsibility to React. You give the input a value prop, so React decides what the input displays. You also give it an onChange handler, so React learns about each edit. The browser never keeps a separate truth. It shows whatever React rendered last.
Here is the shared input from the topic, written as a controlled component.
import { useState } from 'react';
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
export default function App() {
const [text, setText] = useState('');
return (
<>
<Field label="First" value={text} onChange={setText} />
<Field label="Second" value={text} onChange={setText} />
</>
);
}Field has no state of its own. It is a function from props to markup. App owns text, so both inputs always show the same string. This is the single source of truth applied to a form control.
The update cycle
Typing in a controlled input is a round trip. The input does not change itself. It asks the parent to change, and the parent re-renders with a new value.
Three details matter here.
- The event handler runs first, with the value the user just typed. React has not rendered it yet.
setTextschedules a re-render. It does not changetextin the current call. Readingtextright after callingsetTextgives you the old value.- The input displays the new text only after the re-render. If the handler never calls
setState, the typed character does not appear. React resets the DOM value to the prop.
That third point is how a parent can enforce rules. The parent can reject or change an edit before the user sees it.
Controlling more than the text
Because the parent decides what is shown, it can transform input before storing it. This example stores only digits, and it uppercases a separate code field.
import { useState } from 'react';
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
export default function Registration() {
const [phone, setPhone] = useState('');
const [code, setCode] = useState('');
return (
<form>
<Field
label="Phone"
value={phone}
onChange={next => setPhone(next.replace(/\D/g, ''))}
/>
<Field
label="Code"
value={code}
onChange={next => setCode(next.toUpperCase())}
/>
<p>
Stored: {phone || '(empty)'} / {code || '(empty)'}
</p>
</form>
);
}Typing "a" into the phone field does nothing visible. setPhone('') runs with the same value as before, so the input shows what it showed before. The rule lives in the parent, and Field stays reusable.
The child only reports raw text. The parent owns the policy about what counts as valid.
Other controls follow the same pattern
Each form control has one prop for its value and one event for its changes. They are not all value and e.target.value.
| Control | Value prop | Read from event | Notes |
|---|---|---|---|
| `<input type="text">` | `value` | `e.target.value` | A string, never `undefined` or `null` |
| `<textarea>` | `value` | `e.target.value` | Use `value`, not child text, in React |
| `<select>` | `value` on `<select>` | `e.target.value` | Matches an `<option value>` |
| `<input type="checkbox">` | `checked` | `e.target.checked` | A boolean, not `value` |
| `<input type="radio">` | `checked` | `e.target.value` | Compare the group's state to each radio's value |
| `<input type="number">` | `value` | `e.target.value` | Still a string, convert yourself |
| `<input type="file">` | none | `e.target.files` | Always uncontrolled |
Here is a small form that lifts a checkbox and a select into the parent.
import { useState } from 'react';
export default function Preferences() {
const [subscribed, setSubscribed] = useState(false);
const [plan, setPlan] = useState('free');
return (
<form>
<label>
<input
type="checkbox"
checked={subscribed}
onChange={e => setSubscribed(e.target.checked)}
/>
Email me updates
</label>
<label>
Plan:{' '}
<select value={plan} onChange={e => setPlan(e.target.value)}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
</label>
<p>
{subscribed ? 'Subscribed' : 'Not subscribed'} on the {plan} plan.
</p>
</form>
);
}Why a child sometimes should not own the value
A reusable Field could keep its own useState, and that works until another component needs to read or reset the value. Consider a form with a "Clear" button in the parent. If each input hides its value in private state, the parent cannot clear them. It would need refs or a key change to reset them.
With controlled inputs, clearing is one line.
import { useState } from 'react';
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
export default function ClearableForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
function clear() {
setName('');
setEmail('');
}
const canSubmit = name.trim() !== '' && email.includes('@');
return (
<form onSubmit={e => e.preventDefault()}>
<Field label="Name" value={name} onChange={setName} />
<Field label="Email" value={email} onChange={setEmail} />
<button type="button" onClick={clear}>
Clear
</button>
<button type="submit" disabled={!canSubmit}>
Send
</button>
</form>
);
}The parent also computes canSubmit directly from the two values during render. That is a derived value, not a third piece of state. The next chapter covers it in detail.
Controlled and uncontrolled: choosing
| Question | Controlled | Uncontrolled |
|---|---|---|
| Who holds the current value? | React state | The DOM node |
| Can other components read it on every keystroke? | Yes | Only through a ref, on demand |
| Can the parent reset or transform it? | Yes | Awkward |
| Cost | A re-render per keystroke | None |
| Typical use | Linked fields, live validation, formatting | Simple one-shot forms, file inputs |
Re-rendering on each keystroke is rarely a problem for ordinary forms. It becomes a concern only when the parent renders a very large subtree. In that case, move the state down so fewer components re-render.
Edge cases and common errors
Switching from uncontrolled to controlled
If value starts as undefined and later becomes a string, React warns that the component changed from uncontrolled to controlled. This often happens when you initialize state from data that has not loaded yet.
// Risky: user is undefined on the first render
const [user, setUser] = useState();
// <input value={user?.name} ... /> // value is undefined, then a string
// Safer: always pass a string
// <input value={user?.name ?? ''} ... />Pick one mode for the lifetime of the component. Use '' for empty text, never undefined or null.
A value without a handler
If you pass value but no onChange, the input becomes read-only and React warns you. If you really want a read-only field, say so with readOnly. If you meant it to be editable, add the handler.
Passing the wrong thing to onChange
A child written as onChange={e => onChange(e.target.value)} sends a string to the parent. A parent written as onChange={e => setText(e.target.value)} expects an event. Mixing the two gives you undefined.target errors, or an input showing [object Object]. Decide on one contract for each component and keep it.
The contract in this chapter is that the child calls onChange with the new value, not the event. Then onChange={setText} works directly.
Number inputs are still strings
const [qty, setQty] = useState('1');
const total = Number(qty) * 4; // convert when you compute, not when you storeStoring Number(e.target.value) breaks editing. If the user clears the box, Number('') is 0, and the input snaps to "0". The user cannot empty the field to type a new number. Keep the raw string in state, and convert during render.
Transforming input can move the cursor
If your handler rewrites the text, such as adding dashes to a phone number, the browser may jump the caret to the end. Simple transforms like uppercasing a typed character usually behave. Complex formatting needs extra care, or a dedicated input-mask library.
Stale reads after setState
function handleChange(next) {
setText(next);
console.log(text); // still the previous value
}Use next, the value passed to the handler, when you need the new text inside the same event. Do not read the state variable.
Duplicating the value in two places
Do not copy a prop into state, as in const [v, setV] = useState(props.value). That copy is read only on the first render. After that, the parent's updates are ignored and the two values drift apart. This is the same sibling-sync problem, now inside one component. Read the prop directly.
A checklist for a controlled field
- Does the input get its value from a prop or from state, and never both?
- Is the value always a string, or a boolean for
checked? - Does
onChangecall something that changes that state? - Does the child report a value or an event, and does the parent expect the same?
- Does anything that depends on the value get computed during render instead of copied into more state?
Exercise
A teammate writes function Field({ value }) { const [text, setText] = useState(value); return <input value={text} onChange={e => setText(e.target.value)} />; } and renders two of these with the same value from a parent. The parent later changes value, but neither input updates. What is wrong, and how do you fix it?
Show answer
useState(value) reads the prop only on the first render, so Field has its own private copy and ignores later prop changes. That makes it a second source of truth. Remove the local state and make Field controlled: accept value and onChange props, render <input value={value} onChange={e => onChange(e.target.value)} />, and let the parent own the state and pass its setter.
Exercise
A quantity field stores Number(e.target.value) in state. When the user selects the text and presses Backspace, the field shows "0" and they cannot clear it. Why does this happen, and what should the code do instead?
Show answer
Clearing the input produces the empty string, and Number('') is 0. The state becomes 0, so the controlled input renders "0" and the field can never be empty. Store the raw string in state, for example useState(''), and convert with Number(qty) only when you compute something from it during render.