Sub topic 12
Choosing a good state shape
State shape is the structure of the values you pass to useState. A poor shape makes updates error-prone, because the same fact lives in two places and the copies drift apart. A good shape makes bugs hard to write. This chapter assumes you can declare state with useState, update objects and arrays without mutating them, and pass props between components.
Why shape matters
React does not care how you organize state. Any shape works until you have to keep it consistent. Every extra copy of a fact is one more place you must remember to update. If you forget one, the screen shows a contradiction.
Four principles cover most cases:
- Group state that always changes together.
- Avoid contradictions between state variables.
- Avoid redundant state that you can calculate.
- Avoid duplication and deep nesting.
Group related state
If two variables always change together, merge them. A pointer position is a good example, since x and y are never updated alone.
import { useState } from 'react';
function PointerTracker() {
const [position, setPosition] = useState({ x: 0, y: 0 });
return (
<div
style={{ height: 200, border: '1px solid gray' }}
onPointerMove={e => setPosition({ x: e.clientX, y: e.clientY })}
>
Pointer at {position.x}, {position.y}
</div>
);
}One setPosition call replaces both coordinates in a single update. With two separate variables, you could update one and forget the other.
Do not merge everything by reflex. Values that change independently, such as a search query and a theme, are easier to read as separate variables. The test is whether they change together, not whether they are loosely related.
Avoid contradictory state
Suppose a form tracks isSending and isSent as two booleans. Four combinations exist, but only three make sense. If a bug sets both to true, the UI has no correct answer.
Replace the booleans with one variable that holds a status. The impossible combination can no longer be represented.
import { useState } from 'react';
function FeedbackForm() {
const [text, setText] = useState('');
const [status, setStatus] = useState('typing'); // 'typing' | 'sending' | 'sent'
function handleSubmit(e) {
e.preventDefault();
setStatus('sending');
setTimeout(() => setStatus('sent'), 1000);
}
if (status === 'sent') {
return <p>Thanks for your feedback.</p>;
}
const isSending = status === 'sending';
return (
<form onSubmit={handleSubmit}>
<textarea
value={text}
disabled={isSending}
onChange={e => setText(e.target.value)}
/>
<button disabled={isSending}>{isSending ? 'Sending...' : 'Send'}</button>
</form>
);
}isSending here is a local constant calculated from status. It is not state, so it cannot disagree with status. A useful check is to list every combination your variables allow and ask whether each one is possible in your app. If some are not, the shape is too loose.
Avoid redundant state
If you can calculate a value from props or other state during render, do not store it. A stored copy needs a second update every time the source changes. The chapter on derived values covers this in detail. This chapter focuses on a common special case, which is storing an object you already hold elsewhere.
import { useState } from 'react';
function ItemPicker({ items }) {
const [selectedId, setSelectedId] = useState(items[0]?.id ?? null);
const selected = items.find(item => item.id === selectedId);
return (
<>
<ul>
{items.map(item => (
<li key={item.id}>
<button onClick={() => setSelectedId(item.id)}>
{item.id === selectedId ? '> ' : ''}{item.title}
</button>
</li>
))}
</ul>
<p>Selected: {selected ? selected.title : 'nothing'}</p>
</>
);
}The state holds only the id. If the parent renames an item and passes new items, selected reflects the new title on the next render. Had you stored the whole item object in state, it would keep showing the old title, because it is a stale copy.
Avoid duplication
Duplication is the same data stored in several places, for example an item kept in a list and again in a selectedItem variable. It has the same failure as redundant state, and the fix is the same: store one source of truth and refer to it by id.
Avoid deeply nested state
Deep nesting makes updates painful. Changing one leaf means copying every object on the path to it.
// Nested: updating a grandchild requires copying three levels.
const nested = {
id: 0,
title: 'Root',
children: [
{ id: 1, title: 'A', children: [{ id: 3, title: 'A1', children: [] }] },
{ id: 2, title: 'B', children: [] },
],
};
// Flat: every item lives in one lookup table and refers to children by id.
const flat = {
0: { id: 0, title: 'Root', childIds: [1, 2] },
1: { id: 1, title: 'A', childIds: [3] },
2: { id: 2, title: 'B', childIds: [] },
3: { id: 3, title: 'A1', childIds: [] },
};With the flat shape, renaming item 3 is one spread of one entry:
function rename(table, id, title) {
return { ...table, [id]: { ...table[id], title } };
}
console.log(rename(flat, 3, 'Renamed')[3].title); // RenamedFlat state is also easier to render when the same item can appear in several places, because each item exists once. Normalizing adds some bookkeeping, since deleting an item means removing its id from its parent's childIds. Use it when the data is a tree or a graph, not for every list.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| The UI shows two states at once, such as "sending" and "sent" | Several booleans that can both be true | Use one `status` string |
| A list item shows an old title after the parent updates | A copy of the item is stored in state | Store the id and look up the item during render |
| A filtered list is wrong until you click again | The filtered result is stored as state | Calculate it during render |
| Updating one nested field needs many spreads | Deep nesting | Flatten with ids |
| Three `useState` calls are always set together | Related values stored separately | Merge them into one object |
A short checklist
Before you add a state variable, ask three things. Can I calculate this from something I already have? Could this ever disagree with another variable? Does this data already exist elsewhere in state? If the answer to any is yes, change the shape first. Restructuring state while the component is small costs far less than untangling it after several features depend on it.
Exercise
A component keeps const [items, setItems] = useState([...]) and const [selectedItem, setSelectedItem] = useState(items[0]). A user edits the title of the selected item through setItems, but the "Selected" label still shows the old title. Explain why, and show how to fix the state shape.
Show answer
selectedItem holds a separate copy of the object. Editing the list creates a new object for that item, but selectedItem still points to the old one, so the label is stale. Store only the id: const [selectedId, setSelectedId] = useState(items[0]?.id ?? null), then calculate const selected = items.find(i => i.id === selectedId) during render. The label now always reads from the current list.
Exercise
A component has isLoading, isError, and isSuccess booleans. How many combinations can they represent, how many are meaningful if the request can be loading, failed, or succeeded, and what single state variable replaces them?
Show answer
Three booleans give 8 combinations, but only 3 are meaningful, one for each outcome. Replace them with one status variable holding 'loading', 'error', or 'success'. Derive the booleans from it during render if you want them.