Sub topic 3
Controlled inputs: value and onChange
This chapter assumes you know JavaScript objects, arrow functions and destructuring, and that you can write a React component with JSX and call useState. Here you will learn what makes an input controlled and why React needs both value and onChange.
What "controlled" means
A plain HTML input keeps its own text. The browser stores what the user types, and your code reads it later.
A controlled input works differently. React state holds the text, and the input only displays what state says. The state is the single source of truth.
Two props make this work:
valuetells the input what to display.onChangeruns on every keystroke, so you can write the new text back into state.
A worked example
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>
);
}Follow one keystroke through this component:
- The user presses a key.
- The browser fires a change event, and React calls your
onChangehandler with an event objecte. e.targetis the input element, soe.target.valueis the text it now contains.setNamestores that text and schedules a re-render.- React renders again, and the input receives the new
nameas itsvalue.
Because the display always comes from state, the paragraph below the input stays in sync without extra code. Any other part of the component can read name, change it, or clear it, and the input follows.
Why both props are needed
If you set value without onChange, the input becomes read-only. Each keystroke triggers a render, but state has not changed, so React puts the old value back. React also logs a warning in development that you provided a value without an onChange handler.
// Broken: the user cannot type here.
<input value="fixed" />If you only want a fixed, read-only field, add the readOnly attribute to silence the warning and state your intent. If you want an editable field, add onChange.
Common errors
valueset toundefinedornull. If state starts asundefined, React treats the input as uncontrolled. When state later becomes a string, React warns that the input changed from uncontrolled to controlled. Start with an empty string:useState('').- Forgetting
e.target.value. CallingsetName(e)stores the whole event object, and the input shows[object Object]. - Calling the handler during render. Write
onChange={() => setName('x')}oronChange={handleChange}. WritingonChange={handleChange()}runs the function immediately, on every render. - Mutating state. For text, you replace the string, so this rarely goes wrong. It matters more in later chapters, where state is an object.
When controlled inputs help
Controlling an input is useful when you need to react to the value as the user types. Examples include live validation, formatting the text, disabling a button until a field is filled, or showing a preview. Because you can change the state yourself, you can also transform input before it appears. This line stores the text in uppercase:
<input value={code} onChange={(e) => setCode(e.target.value.toUpperCase())} />The cost is that every keystroke re-renders the component. For most forms this is unnoticeable, and a later chapter covers when it matters.
Exercise
A developer writes <input value={email} /> with const [email, setEmail] = useState(''), and the user cannot type in the field. Why does this happen, and what is the fix?
Show answer
The input is controlled by email, but nothing updates that state. Each keystroke triggers a render, and React restores the old empty value. Add an onChange handler that writes the typed text back: onChange={(e) => setEmail(e.target.value)}.
Exercise
A field uses useState() with no argument and <input value={name} onChange={...} />. What warning appears once the user types, and how do you prevent it?
Show answer
React warns that the component is changing an uncontrolled input to be controlled, because name starts as undefined and then becomes a string. Initialize state with an empty string: useState('').