Structuring state
Overview
Choosing what to keep in state matters as much as how you update it. Well-structured state makes components easy to change and hard to break; poorly structured state leads to values that drift out of sync and bugs that only appear after a specific sequence of clicks.
The guiding principle is the same one used in database design: don’t store the same information twice.
Principle 1: Don’t store what you can calculate
// ✗ fullName duplicates firstName + lastName
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [fullName, setFullName] = useState('');
function handleFirstNameChange(e) {
setFirstName(e.target.value);
setFullName(e.target.value + ' ' + lastName); // easy to forget somewhere
}// ✓ calculate it during render
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const fullName = `${firstName} ${lastName}`.trim();The component re-renders whenever firstName or lastName changes, so fullName is recalculated automatically. It can never be wrong.
The same goes for counts, totals, filtered lists, “is the form valid?” flags and anything else derived from existing data:
const visibleCourses = courses.filter((c) => c.title.toLowerCase().includes(query.toLowerCase()));
const isFormValid = email.includes('@') && password.length >= 8;“Isn’t recalculating every render slow?” Almost never — filtering a few hundred items takes microseconds. If you measure a genuinely expensive calculation, you can cache it with
useMemoor let React Compiler do it (see Performance).
Principle 2: Don’t duplicate objects
// ✗ selectedCourse is a copy of an item in courses
const [courses, setCourses] = useState(initialCourses);
const [selectedCourse, setSelectedCourse] = useState(null);If the user renames the selected course, courses updates but selectedCourse still holds the old copy. Store the id instead and look the item up:
// ✓ one source of truth
const [courses, setCourses] = useState(initialCourses);
const [selectedId, setSelectedId] = useState(null);
const selectedCourse = courses.find((c) => c.id === selectedId);Principle 3: Avoid contradictions
// ✗ these can disagree: isSending and isSent both true?
const [isSending, setIsSending] = useState(false);
const [isSent, setIsSent] = useState(false);
const [isError, setIsError] = useState(false);Three booleans allow eight combinations, but only four make sense. Replace them with one status value:
// ✓ exactly one status at a time
const [status, setStatus] = useState('idle'); // 'idle' | 'sending' | 'sent' | 'error'
const isSending = status === 'sending';
const isSent = status === 'sent';Impossible states are now literally impossible to represent.
Principle 4: Group related state
If two values always change together, put them in one object:
// Mouse position: x and y always update together
const [position, setPosition] = useState({ x: 0, y: 0 });
setPosition({ x: e.clientX, y: e.clientY });Keep independent values separate — they’re simpler to update:
// ✓ these change independently
const [query, setQuery] = useState('');
const [page, setPage] = useState(1);Principle 5: Prefer flat over deeply nested
Deeply nested state (a tree of folders inside folders) is painful to update immutably — every change means copying every level. Normalise it like a database: store items in a flat collection keyed by id, and reference children by id.
// Flat: easy to update any item without copying its ancestors
const [lessons, setLessons] = useState({
1: { id: 1, title: 'Intro', childIds: [2, 3] },
2: { id: 2, title: 'Setup', childIds: [] },
3: { id: 3, title: 'JSX', childIds: [] },
});
function rename(id, title) {
setLessons({ ...lessons, [id]: { ...lessons[id], title } });
}Don’t mirror props in state
// ✗ color only uses the prop's FIRST value
function Badge({ color }) {
const [badgeColor, setBadgeColor] = useState(color);
return <span style={{ color: badgeColor }}>New</span>;
}useState(color) only uses its argument on the first render. If the parent later passes a different color, the badge ignores it. Just use the prop directly:
function Badge({ color }) {
return <span style={{ color }}>New</span>;
}The one legitimate case is when you want to ignore later updates — an editable copy of an initial value. Make that obvious with the name:
function NoteEditor({ initialText }) {
const [text, setText] = useState(initialText); // later changes to initialText are ignored on purpose
}A checklist
Before adding a state variable, ask:
- Does it change over time? If not, it’s a constant.
- Is it passed in from a parent? Then it’s a prop, not state.
- Can I compute it from existing props or state? Then compute it.
- Does it duplicate something? Store an id or a single status instead.
What’s left is the true, minimal state of your component.
Thinking in React: the React docs’ classic approach to building a UI is — break it into components, build a static version with props, find the minimal state, decide where that state lives, then add the event handlers that update it. This chapter covers steps 3 and 4.
Fix the redundant state
This cart keeps items, itemCount, total and selectedItem in state, and has bugs: the count and total drift out of sync, and the selected item shows a stale quantity after you change it. Refactor so that only items and selectedId are state, and everything else is calculated during render.
import { useState } from 'react';
export function Cart({ initialItems }) {
const [items, setItems] = useState(initialItems);
const [itemCount, setItemCount] = useState(initialItems.length);
const [total, setTotal] = useState(0);
const [selectedItem, setSelectedItem] = useState(null);
function changeQty(id, qty) {
setItems(items.map((i) => (i.id === id ? { ...i, qty } : i)));
}
// …renders items, itemCount, total and selectedItem.qty
}import { useState } from 'react';
export function Cart({ initialItems }) {
const [items, setItems] = useState(initialItems);
const [selectedId, setSelectedId] = useState(null);
// Derived during render — always in sync
const itemCount = items.reduce((n, i) => n + i.qty, 0);
const total = items.reduce((sum, i) => sum + i.qty * i.price, 0);
const selectedItem = items.find((i) => i.id === selectedId) ?? null;
function changeQty(id, qty) {
setItems(items.map((i) => (i.id === id ? { ...i, qty } : i)));
}
return (
<section>
<ul>
{items.map((i) => (
<li key={i.id}>
<button onClick={() => setSelectedId(i.id)}>{i.title}</button>
<input
type="number"
min="1"
aria-label={`Quantity of ${i.title}`}
value={i.qty}
onChange={(e) => changeQty(i.id, Number(e.target.value))}
/>
</li>
))}
</ul>
<p>{itemCount} items · ${total.toFixed(2)}</p>
{selectedItem && <p>Selected: {selectedItem.title} × {selectedItem.qty}</p>}
</section>
);
}Summary
- Keep state minimal: if you can compute a value from props or other state, compute it during render.
- Don’t duplicate data in state — store the id of the selected item, not a copy of the item.
- Group values that always change together into one object; keep independent values separate.
- Avoid contradictions: one
statusvalue beats several booleans that can disagree. - Don’t copy props into state unless you deliberately want to ignore later updates — then name it
initialX.