Sub topic 15
Keeping State Flat to Avoid Deep Updates
This chapter assumes you know how to update objects and arrays with spread, map, and filter, and that you have used useState in function components. Here you will see why deeply nested state is painful to update, and how to reshape it so updates stay short.
The problem with deep nesting
Nested state forces you to copy every object along the path to the value you change. One level of nesting needs two spreads. Three levels need three. Each extra level adds more places to make a mistake, such as forgetting a spread and mutating the original object by accident.
Consider a trip planner where places are nested inside continents, and continents inside a root object:
const [plan, setPlan] = useState({
id: 0,
title: '(Root)',
childPlaces: [
{
id: 1,
title: 'Earth',
childPlaces: [
{ id: 2, title: 'Africa', childPlaces: [] },
{ id: 3, title: 'Asia', childPlaces: [] },
],
},
],
});Removing "Asia" means rebuilding "Earth", then the root, with map and filter at each level. The code is hard to read, and it gets worse as the tree gets deeper.
Flatten the structure
Instead of nesting, store every item in one flat lookup table keyed by id. Each item lists the ids of its children, not the children themselves.
const [plan, setPlan] = useState({
0: { id: 0, title: '(Root)', childIds: [1] },
1: { id: 1, title: 'Earth', childIds: [2, 3] },
2: { id: 2, title: 'Africa', childIds: [] },
3: { id: 3, title: 'Asia', childIds: [] },
});Now every item sits at the same depth. Any change needs only one level of copying.
Updating flat state
Renaming an item touches one entry in the table:
function handleRename(id, title) {
setPlan({
...plan,
[id]: { ...plan[id], title },
});
}Removing a child means editing its parent's childIds list. You also delete the child's own entry:
function handleRemove(parentId, childId) {
const parent = plan[parentId];
const { [childId]: removed, ...rest } = plan;
setPlan({
...rest,
[parentId]: {
...parent,
childIds: parent.childIds.filter((id) => id !== childId),
},
});
}The destructuring { [childId]: removed, ...rest } copies every entry except childId into rest. Nothing is mutated.
If the removed item has children of its own, their entries stay in the table as orphans. They take memory but cause no visible bug, because nothing refers to them. For a small table you can leave them. For a large one, remove them recursively.
Reading flat state
A flat table changes how you render. A component receives an id and looks up its own data and its children:
function PlaceTree({ id, plan }) {
const place = plan[id];
return (
<li>
{place.title}
{place.childIds.length > 0 && (
<ol>
{place.childIds.map((childId) => (
<PlaceTree key={childId} id={childId} plan={plan} />
))}
</ol>
)}
</li>
);
}When to flatten
Flattening is a trade-off, not a rule.
| Situation | Suggestion |
|---|---|
| Two or three levels, rarely updated | Keep it nested and use spread |
| Same item appears in several places | Flatten, so there is one copy to update |
| Tree of unknown depth | Flatten |
| Many deep updates and you want less code | Consider Immer, covered next |
Exercise
A state object holds { items: [{ id: 1, tags: [...] }] }, and a separate selectedItem copy of one of those item objects. Why does renaming an item in items leave the screen showing the old name for the selected item, and what change to the state shape fixes it?
Show answer
selectedItem is a separate copy of the object, so updating items does not change it. Store selectedId instead of the object, and look up the selected item in items when rendering. Then there is only one copy of the data to update.