Sub topic 2
Storing input values in state
This chapter assumes you know JavaScript destructuring, function components, JSX, and how to attach an event handler such as onClick. You should also be comfortable with basic HTML form elements. The chapter covers how useState holds what a user types. The next chapter explains why the input needs both value and onChange.
Why an input value belongs in state
A plain HTML input keeps its own text inside the browser's DOM. React components can't see that text until you ask for it. If you want to show it elsewhere, check it, or send it to a server, it's easier when the text lives in your component.
useState gives a component a value that survives re-renders, plus a setter function. When you call the setter, React stores the new value and calls your component again. The returned JSX then reflects the new value.
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>
);
}Here name is the current text and setName replaces it. The onChange handler reads e.target.value, which is the text in the input after the keystroke, and passes it to setName. React then re-renders, and the input and the greeting both show the new text.
The update cycle
The cycle runs once per keystroke. State is the only place the text is stored, so the screen always shows what state holds.
Choosing the initial value
The argument to useState is the starting value, and it is used only on the first render. For a text input, use an empty string, not undefined. If value starts as undefined and later becomes a string, React warns that the input changed from uncontrolled to controlled. Starting with '' avoids this.
For a record loaded from elsewhere, pass its field as the initial value, for example useState(user.name). Be aware that later changes to user do not update the state. A later chapter covers resetting and the key technique that handles this.
State updates are not immediate
A setter does not change the variable in the current render. It asks React to render again with a new value. Code that runs right after the call still sees the old value.
import { useState } from 'react';
export default function Counter() {
const [text, setText] = useState('');
function handleChange(e) {
setText(e.target.value);
console.log(text); // logs the previous value, not e.target.value
}
return <input value={text} onChange={handleChange} />;
}If you need the new text in the same handler, use e.target.value directly or store it in a local variable first.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Warning about uncontrolled to controlled | Initial state is `undefined` | Start with `''` |
| Input won't accept typing | `value` is set but `onChange` is missing or does nothing | Call the setter in `onChange` |
| Logged value is one keystroke behind | Reading state right after calling the setter | Use `e.target.value` |
| Typed text is a number type problem | `value` from an input is always a string | Convert with `Number(value)` when needed |
Exercise
A component declares const [city, setCity] = useState(); and renders <input value={city} onChange={(e) => setCity(e.target.value)} />. React logs a warning after the first keystroke. What causes it, and what is the fix?
Show answer
The initial state is undefined, so the input starts uncontrolled. After the first keystroke city becomes a string and the input turns controlled, which triggers the warning. Fix it by starting with an empty string: useState('').