Sub topic 3
Controlled inputs: value and onChange
What you should already know
This chapter assumes you can write a React function component, use JSX, and read state with useState. It also assumes you know how to pass an event handler such as onClick, and that you are comfortable with arrow functions and destructuring. The previous chapters covered events and state. This chapter combines them.
What "controlled" means
An HTML input normally keeps its own value. You type, the browser updates the text, and the DOM node remembers it. React can leave that arrangement alone, which gives you an uncontrolled input (covered in a later chapter).
A controlled input is different. React state holds the value, and the input only displays what state tells it to display. State is the single source of truth. The DOM is a view of that state.
Two props make this work:
valuesets what the input shows.onChangeruns when the user edits the input. Its job is to write the new text back into state.
import { useState } from 'react';
export default function NameField() {
const [name, setName] = useState('');
return (
<label>
Name
<input value={name} onChange={(e) => setName(e.target.value)} />
<p>Hello, {name || 'stranger'}</p>
</label>
);
}The loop, step by step
Typing a letter in a controlled input starts a cycle:
- The user presses a key. The browser fires an input event.
- React calls your
onChangehandler with a synthetic event object. - The handler reads
e.target.value, which is the text the input would show if React allowed the change. - The handler calls
setName(newText), which schedules a re-render. - React re-renders the component. The
valueprop now holds the new text, and React writes it to the DOM node.
The key point is that React does not accept the keystroke on its own authority. The browser proposes a new value, your handler decides whether to store it, and the next render decides what the input shows.
Why both props are required
value and onChange work as a pair. Each one alone causes a problem.
| What you write | What happens |
|---|---|
| `value` with no `onChange` | The input is locked to the state value and the user cannot type. React logs a warning that you provided a `value` prop without an `onChange` handler. |
| `onChange` with no `value` | The input is uncontrolled. The handler runs, but the DOM owns the text. |
| `value` and `onChange` | The input is controlled. |
| `value` with `readOnly` and no `onChange` | Allowed. The input displays state and is deliberately not editable. |
If you want a field the user cannot edit, use readOnly or disabled so the intent is explicit and the warning goes away.
Because React is in charge, you can intercept input
The handler sits between the keystroke and the state update. That lets you transform or reject input before it appears.
import { useState } from 'react';
export default function PostalCode() {
const [code, setCode] = useState('');
function handleChange(e) {
const digitsOnly = e.target.value.replace(/\D/g, '').slice(0, 5);
setCode(digitsOnly);
}
return (
<label>
Postal code
<input
value={code}
onChange={handleChange}
inputMode="numeric"
autoComplete="postal-code"
/>
</label>
);
}If the user types a, the handler computes '', state stays '', and the input shows nothing new. The character never appears. You can use the same technique to uppercase text, trim spaces, or cap length.
This is also how you derive display values. In the first example, the greeting is computed from name during render. It needs no second piece of state.
Common errors
Initializing state with `undefined` or `null`
If the initial value is undefined, React treats the input as uncontrolled. When state later becomes a string, React warns that the component is changing an uncontrolled input to be controlled. null is similar and also triggers a warning.
// Bug: user.nickname may be undefined on the first render
const [nickname, setNickname] = useState(user.nickname);
// Fix: always provide a string
const [nickname, setNickname] = useState(user.nickname ?? '');Use '' for text inputs, even when "no value yet" is the real meaning.
Reading the event after the handler returns
Read what you need from the event synchronously, or use the functional form of the setter when a state update depends on the previous state. For a plain text field, setName(e.target.value) is correct because the value is read immediately.
Using `defaultValue` with `value`
Do not pass both value and defaultValue. React warns, and value wins. Pick one model per input. For a controlled input, put the starting text in useState.
Mutating state instead of replacing it
Controlled inputs backed by objects or arrays need new objects on each update. The next chapter shows the pattern for objects. For now, remember that form.name = e.target.value does not trigger a re-render.
Defining the component inside another component
If you declare a component function inside the body of another component, React sees a new component type on every render. It unmounts and remounts the input, so focus is lost after each keystroke. Define components at module level.
// Bug: Field is recreated on every render of Page
function Page() {
const [text, setText] = useState('');
function Field() {
return <input value={text} onChange={(e) => setText(e.target.value)} />;
}
return <Field />;
}Move Field outside Page and pass text and setText as props.
Quirks of `onChange` in React
In plain HTML, the change event fires when the user finishes editing, usually on blur. React's onChange for text inputs behaves like the browser's input event: it fires on every keystroke, paste, cut, and autofill. That is what makes live updates possible. Handlers attached with onInput also work, but onChange is the convention React documents and the one form libraries expect.
The value of a text input is always a string. A type="number" input still gives you a string in e.target.value, so convert it yourself when you need a number, and decide what an empty string means.
Resetting state when the record changes
A controlled input uses useState once, for its initial value. If a parent passes a new user prop later, the old state remains. You can avoid this without an effect by giving the form a key. A new key makes React discard the old instance and create a fresh one with fresh initial state.
import { useState } from 'react';
function ProfileForm({ user }) {
const [name, setName] = useState(user.name);
return (
<input value={name} onChange={(e) => setName(e.target.value)} />
);
}
export default function ProfilePage({ user }) {
return <ProfileForm key={user.id} user={user} />;
}When user.id changes, ProfileForm remounts and useState(user.name) runs again with the new user. Typed but unsaved text for the previous user is discarded, which is usually what you want when switching records.
Cursor position and formatting
Because the DOM value is set from state on each render, React normally keeps the caret where it was. If your handler changes the text in the middle of the string, for example by inserting dashes into a phone number, the caret can jump to the end. Fixing that requires refs and setSelectionRange, which is a reason to consider a masking library for heavily formatted fields.
When controlled inputs are the right choice
Choose controlled inputs when you need to:
- Validate or format as the user types.
- Disable a submit button until the form is valid.
- Show a live preview, character count, or filtered list.
- Change one field based on another.
- Set or reset the value from code.
Each of these needs the value in state while the user is still typing. If you need none of them, an uncontrolled input is simpler, and a later chapter covers it.
Checklist
- Every controlled input has a
valueand anonChange. - Initial state is a string for text inputs, never
undefined. - The handler writes
e.target.value(or a transformed version of it) into state. - Components that contain inputs are defined at module level.
- A
keyresets state when the form edits a different record.
Exercise
A developer writes <input value={email} /> with const [email, setEmail] = useState(''). The input shows an empty box and ignores typing. Why, and what is the minimal fix?
Show answer
The input is controlled by value, but nothing updates email, so each render puts the same empty string back. React also warns about a value prop with no onChange. Add onChange={(e) => setEmail(e.target.value)}. If the field should not be editable, add readOnly instead.
Exercise
A user profile form is built with useState(user.name). When the app switches from user 1 to user 2, the input still shows user 1's name. Give two ways to fix it.
Show answer
One fix is to render the form with a key, such as <ProfileForm key={user.id} user={user} />, so React creates a new instance with fresh state when the id changes. The other is to lift the state up to the parent so it controls the value and resets it when the selected user changes.
Exercise
Write an onChange handler for a controlled text input that stores the text in uppercase and allows at most 10 characters.
Show answer
function handleChange(e) { setCode(e.target.value.toUpperCase().slice(0, 10)); }. The handler transforms the proposed value before it goes into state, and the input then displays the stored value.