Sub topic 2
Storing input values in state
This chapter assumes you know JavaScript destructuring and arrow functions, can write a basic React component in JSX, and have seen useState once. It covers how to keep what a user types in component state, and how that state behaves. The next chapter explains why an input needs both value and onChange. Here the focus is the state side.
Why a plain variable is not enough
A React component is a function that runs again each time React renders it. Local variables are created fresh on every run. React only re-renders when it is told that state changed, and an assignment to a local variable gives it no such signal.
export default function Broken() {
let name = '';
return (
<input
value={name}
onChange={(e) => {
name = e.target.value;
}}
/>
);
}Typing into this field appears to do nothing. The handler changes name, but React never renders again, so the input keeps showing the value it was given (an empty string). Even if a render did happen, let name = '' would run again and discard the typed text.
State fixes both problems. React stores the value outside the function, so it survives between renders, and calling the setter schedules a new render.
Storing the value with useState
useState(initialValue) returns a pair: the current value and a setter function.
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 sequence for each keystroke is:
- The browser fires a change event. React calls your
onChangehandler with an event object. e.target.valueis the text currently in the DOM input. You pass it tosetName.- React stores the new value and calls
NameFieldagain. - This time
useStatereturns the new string, sonamehas the typed text, and React updates the input and the paragraph.
State is a snapshot
Inside one render, name is a constant. It holds the value React gave this render, and it does not change when you call the setter. The setter only affects the next render.
import { useState } from 'react';
export default function SnapshotDemo() {
const [name, setName] = useState('');
function handleChange(e) {
setName(e.target.value);
console.log('state:', name, 'input:', e.target.value);
}
return <input value={name} onChange={handleChange} />;
}If you type a, then b, the console prints state: input: a and then state: a input: ab. The state value is always one keystroke behind the input inside the handler. This is the most common surprise for people new to React state.
The rule that follows: inside a handler, use the value you just received (e.target.value) when you need the new text immediately. Use the state variable when rendering.
Updating from the previous value
When the new value depends on the old one, pass a function to the setter. React calls it with the latest queued state.
import { useState } from 'react';
export default function TagInput() {
const [text, setText] = useState('');
const [tags, setTags] = useState([]);
function addTag() {
const trimmed = text.trim();
if (trimmed === '') return;
setTags((prev) => [...prev, trimmed]);
setText('');
}
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button type="button" onClick={addTag}>Add tag</button>
<ul>
{tags.map((tag, index) => (
<li key={`${tag}-${index}`}>{tag}</li>
))}
</ul>
</div>
);
}Two details here:
setTags((prev) => [...prev, trimmed])creates a new array. React compares state withObject.is, so mutating the old array withpushwould not trigger a render.- Setting
textback to''clears the input, because the input displays whatevertextholds. You get this behavior for free once the state is the source of the displayed value.
For a single text field, the plain form setName(e.target.value) is fine, since the new value does not depend on the old one. The function form matters when several updates can queue in one event, or when you build objects and arrays from earlier state.
Choosing the initial value
The argument to useState is used only on the first render. Later renders ignore it. Three cases come up with forms.
Empty string, not undefined
Start text inputs with ''. If you start with undefined (for example useState() or useState(user.nickname) where the nickname is missing), React treats the input as uncontrolled. When state later becomes a string, React logs a warning that the component changed from uncontrolled to controlled. Fall back to an empty string:
const [nickname, setNickname] = useState(user.nickname ?? '');Expensive or external initial values
If computing the initial value costs something, such as reading localStorage, pass a function. React calls it once, on the first render, instead of on every render.
import { useState } from 'react';
export default function DraftNote() {
const [draft, setDraft] = useState(() => localStorage.getItem('draft') ?? '');
function handleChange(e) {
const next = e.target.value;
setDraft(next);
localStorage.setItem('draft', next);
}
return <textarea value={draft} onChange={handleChange} />;
}This example uses the next local constant from the warning above. It also assumes the code runs in a browser. In a server-rendered app, localStorage does not exist on the server, so you would need a different approach.
Props as initial values
useState(user.name) copies the prop once. If the parent later passes a different user, the state does not follow. The chapter on initial values and resetting covers how to handle that. For now, remember that the initial argument is a starting point, not a live link.
Everything in an input is a string
e.target.value is always a string, even for type="number". If you store it as is, comparisons and arithmetic can go wrong:
import { useState } from 'react';
export default function QuantityField() {
const [quantity, setQuantity] = useState('1');
const parsed = Number(quantity);
const total = parsed * 4.5;
return (
<label>
Quantity
<input
type="number"
min="0"
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
/>
<p>Total: {Number.isNaN(total) ? '-' : total.toFixed(2)}</p>
</label>
);
}The state holds the string, because that is what the user is editing. While the field is empty or half typed, such as - or 1., a stored number would fight the user's typing. Convert at the point of use, and handle NaN. An empty string converts to 0 with Number(''), so check for quantity === '' if you need to tell "empty" apart from "zero".
Keep state minimal: derive the rest
State should hold only what cannot be computed from other values. Counters, trimmed text, and validity flags can all be computed during render.
import { useState } from 'react';
const LIMIT = 80;
export default function BioField() {
const [bio, setBio] = useState('');
const remaining = LIMIT - bio.length;
const isTooLong = remaining < 0;
return (
<div>
<label htmlFor="bio">Bio</label>
<textarea id="bio" value={bio} onChange={(e) => setBio(e.target.value)} />
<p>{isTooLong ? `${-remaining} characters over` : `${remaining} left`}</p>
</div>
);
}Storing remaining or isTooLong in separate state would create more things to keep in sync. If you forgot to update one of them, the screen would contradict itself. Computing them during render means they are correct by construction.
| Value | Store in state? | Reason |
|---|---|---|
| Text the user typed | Yes | Cannot be derived from anything else |
| Character count | No | `bio.length` |
| Trimmed or lowercased text | No | Compute with `trim()` or `toLowerCase()` when used |
| "Is the form empty?" | No | Compare the fields during render |
| Error messages after submit | Yes | They record the result of a past event, not the current values |
One state variable per field, for now
With a few unrelated fields, separate useState calls are clear and easy to read:
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');This gets repetitive as a form grows. The chapter on one state object for many fields shows how to combine them. Until then, separate variables are a fine choice for two or three inputs.
Common mistakes
- Mutating state directly, for example
tags.push(x)orform.email = value, then calling the setter with the same object. React sees the same reference and skips the update. - Reading state right after the setter and getting the old value.
- Initializing with
undefinedornulland triggering the controlled/uncontrolled warning. - Storing numbers as numbers and breaking intermediate input such as
-or0.. - Duplicating derived values in state.
Exercise
A component has const [city, setCity] = useState(''); and this handler: function handleChange(e) { setCity(e.target.value); console.log(city.length); }. The user types "Rome" one letter at a time. What values does the console print, and what would you change to log the length of the text the user just typed?
Show answer
It prints 0, 1, 2, 3. Within one render, city is a snapshot of the value from before the setter call, so the log is always one keystroke behind. To log the new length, read it from the event instead: const next = e.target.value; setCity(next); console.log(next.length);, which prints 1, 2, 3, 4.
Exercise
You need to show a live "words typed" count under a textarea whose text is stored in notes state. Should the word count be a second useState variable? Explain, and write the expression you would use.
Show answer
No. The count can be computed from notes during render, so a second state variable would only add a chance of the two going out of sync. For example: const wordCount = notes.trim() === '' ? 0 : notes.trim().split(/\s+/).length;.