Sub topic 15
Keeping State Flat to Avoid Deep Updates
This chapter assumes you can write the copy patterns from earlier chapters: object spread, nested object updates, and map/filter on arrays of objects. It also assumes you know useState and updater functions. Here you will see why those patterns get awkward as state nests deeper, and how to reshape the state so they stay simple.
Why deep nesting hurts
Every copy-based update must copy each object on the path from the root to the changed value. A change one level down costs one extra spread. In a tree of unknown depth, such as a folder tree, a comment thread, or a travel plan, the path length is not fixed. You need recursion, and every update rebuilds every ancestor.
Here is a nested travel plan and a rename function for it:
const initialPlan = {
id: 0,
title: 'Trip',
children: [
{
id: 1,
title: 'Europe',
children: [
{ id: 2, title: 'Paris', children: [] },
{ id: 3, title: 'Rome', children: [] },
],
},
{ id: 4, title: 'Asia', children: [{ id: 5, title: 'Tokyo', children: [] }] },
],
};
function renameNode(node, id, title) {
if (node.id === id) {
return { ...node, title };
}
return {
...node,
children: node.children.map((child) => renameNode(child, id, title)),
};
}
console.log(renameNode(initialPlan, 5, 'Kyoto').children[1].children[0].title);This works, and it does not mutate the original. It also has three costs:
- Every node is visited and every ancestor of the target gets a new object, so unrelated branches also need a walk.
- Each operation (rename, delete, add child, move) needs its own recursive function.
- Moving a node from one parent to another means editing two places in the tree at once, which is hard to get right.
Flatten: one lookup table, references by id
The fix is to store each item once, in a plain object keyed by id. A parent no longer contains its children. It holds a list of their ids.
const initialPlan = {
0: { id: 0, title: '(root)', childIds: [1, 4] },
1: { id: 1, title: 'Europe', childIds: [2, 3] },
2: { id: 2, title: 'Paris', childIds: [] },
3: { id: 3, title: 'Rome', childIds: [] },
4: { id: 4, title: 'Asia', childIds: [5] },
5: { id: 5, title: 'Tokyo', childIds: [] },
};The tree structure is still there. It now lives in the childIds arrays instead of in object nesting. Every node sits at the same depth, so any update touches at most the node itself and its parent.
The diagram shows the same data in both shapes.
Updates on flat state
Renaming replaces one entry. A computed key ([id]) selects which entry to replace:
function renamePlace(plan, id, title) {
return { ...plan, [id]: { ...plan[id], title } };
}Adding a child creates a new entry and updates the parent's id list. Both changes go into a single new object so React sees one consistent state:
function addPlace(plan, parentId, newId, title) {
const parent = plan[parentId];
return {
...plan,
[newId]: { id: newId, title, childIds: [] },
[parentId]: { ...parent, childIds: [...parent.childIds, newId] },
};
}Removing a child is where flat state needs one extra step. If you only filter the id out of the parent's childIds, the entry stays in the table as an orphan, along with its descendants. Collect the whole subtree and drop it from the copy:
function removePlace(plan, parentId, id) {
const next = { ...plan };
const parent = plan[parentId];
next[parentId] = {
...parent,
childIds: parent.childIds.filter((childId) => childId !== id),
};
const stack = [id];
while (stack.length > 0) {
const current = stack.pop();
stack.push(...plan[current].childIds);
delete next[current];
}
return next;
}delete next[current] is safe because next is a fresh object that you created in this function. You are not mutating the state object. The entries inside it are shared with the old state, and you never write to them.
Moving a node is now two small edits: remove its id from the old parent's childIds and add it to the new parent's. Neither edit needs recursion.
Using it in a component
Each component receives an id and reads its own entry from the table. The updater form setPlan((prev) => ...) keeps handlers correct even if several fire before a re-render.
import { useState } from 'react';
const initialPlan = {
0: { id: 0, title: '(root)', childIds: [1, 4] },
1: { id: 1, title: 'Europe', childIds: [2, 3] },
2: { id: 2, title: 'Paris', childIds: [] },
3: { id: 3, title: 'Rome', childIds: [] },
4: { id: 4, title: 'Asia', childIds: [5] },
5: { id: 5, title: 'Tokyo', childIds: [] },
};
function removePlace(plan, parentId, id) {
const next = { ...plan };
const parent = plan[parentId];
next[parentId] = {
...parent,
childIds: parent.childIds.filter((childId) => childId !== id),
};
const stack = [id];
while (stack.length > 0) {
const current = stack.pop();
stack.push(...plan[current].childIds);
delete next[current];
}
return next;
}
function Place({ id, parentId, plan, onRemove }) {
const place = plan[id];
return (
<li>
{place.title}{' '}
{parentId !== null && (
<button onClick={() => onRemove(parentId, id)}>Remove</button>
)}
{place.childIds.length > 0 && (
<ul>
{place.childIds.map((childId) => (
<Place
key={childId}
id={childId}
parentId={id}
plan={plan}
onRemove={onRemove}
/>
))}
</ul>
)}
</li>
);
}
export default function TravelPlan() {
const [plan, setPlan] = useState(initialPlan);
function handleRemove(parentId, id) {
setPlan((prev) => removePlace(prev, parentId, id));
}
return (
<ul>
<Place id={0} parentId={null} plan={plan} onRemove={handleRemove} />
</ul>
);
}Store ids, not copies
Flattening also removes a second kind of bug: duplicated data. Suppose you keep a selectedPlace object in state next to the list of places. When the user renames that place, the list holds the new title and selectedPlace still holds the old one, because they are two separate objects. Store the id instead and look the object up when you render:
const [selectedId, setSelectedId] = useState(null);
const selectedPlace = selectedId === null ? null : plan[selectedId];There is now one source of truth. The same applies to any value you can compute from state. Compute it during rendering instead of storing it.
Trade-offs and edge cases
- Orphans. Flat state does not enforce consistency. A bug can leave an id in
childIdswith no matching entry, or an entry nobody references. Keep structural edits in a few helper functions such asaddPlaceandremovePlace, so the invariants live in one place. - Reading is slightly harder. To render or search the tree you resolve ids through the table. Rendering needs the lookup shown in
Place. The nested form was easier to read but harder to write. - Ordering. A plain object keyed by id has no meaningful order for display. Keep order in arrays of ids, as
childIdsdoes. For a flat list, a single array of ids plus a table works the same way. - Key types. Object keys are always strings, so
plan[2]andplan['2']are the same entry. Ids stored inchildIdscan stay numbers, and lookups still work. If you compare keys obtained fromObject.keys, convert them first. - Cycles. Nested objects cannot contain a cycle, but id references can. A node listing its own ancestor in
childIdsmakesremovePlaceloop forever and the renderer recurse without end. Validate moves before applying them. - Not always worth it. A form object with one nested
addressis fine as is. Flatten when the depth is open-ended, when the same item appears in several places, or when you often update items by id.
Exercise
In the flat travel plan, write a function movePlace(plan, id, fromId, toId) that moves node id from parent fromId to parent toId without mutating plan. Why does it not need recursion?
Show answer
function movePlace(plan, id, fromId, toId) { const from = plan[fromId]; const to = plan[toId]; return { ...plan, [fromId]: { ...from, childIds: from.childIds.filter((c) => c !== id) }, [toId]: { ...to, childIds: [...to.childIds, id] }, }; } It needs no recursion because the moved node's own entry and its descendants never change. Only the two parents' childIds arrays change, and both parents are reached directly by id. (If fromId equals toId the second entry overwrites the first, so guard against that case.)