Sub topic 10
Keys, row state, and memoization
This chapter assumes you know how React reconciles lists with key, how useState ties state to a component instance, and how React.memo skips re-renders. It also assumes you have built the fixed-height list and used useVirtualizer from the earlier chapters. Virtualization changes two things you may take for granted: which component instances exist, and how often they re-render.
Why rows behave differently in a virtual list
In a normal list, every row stays mounted. In a virtual list, a row mounts when it enters the rendered window and unmounts when it leaves. Scrolling down and back up creates fresh component instances for the same data.
This has three consequences:
- Local state (
useState, uncontrolled input values, focus) disappears when a row unmounts. - Keys decide which DOM node and which state a row gets when the window shifts or the data changes.
- Every scroll event can re-render the parent, so every visible row re-renders unless you prevent it.
Keys: use identity, not position
The hand-written list used key={i}, where i is the row index. That is acceptable only when the list never reorders, filters, or inserts. Otherwise the key follows the position and not the item.
Suppose you prepend a new item to a list of expandable rows. With index keys, the row at index 0 keeps its instance, and with it any local state, but now shows different data. The old item's "expanded" flag appears on the new item. React is not wrong here. You told it that position 0 is the same row as before.
Use a stable identifier from your data, such as a database id:
rows.push(
<div key={items[i].id} style={{ position: "absolute", top: i * rowHeight, left: 0, right: 0, height: rowHeight }}>
{items[i].label}
</div>
);Do not generate keys with Math.random() or crypto.randomUUID() during render. A new key on every render forces React to unmount and remount every row on every scroll event.
Keys in TanStack Virtual
useVirtualizer assigns each virtual item a key, which is the index by default. Two things depend on that key:
- The
keyyou put on the row element. - The cache of measured row heights, in dynamic-size lists.
If you leave the default, the measured height of index 12 stays attached to index 12 after you insert an item above it. The row then renders with the wrong height until it is measured again. Pass getItemKey so that both keys and measurements follow the item:
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 40,
overscan: 5,
getItemKey: (index) => items[index].id,
});The function receives an index and must return a unique, stable value for that item. Use v.key as the React key and read the item with items[v.index].
Where row state should live
Because rows unmount, state that must survive scrolling cannot live inside the row. The options:
| State | Where to keep it | Survives scroll-out? |
|---|---|---|
| Purely visual, safe to lose (hover, a tooltip open) | `useState` in the row | No, and that is fine |
| Expanded, selected, edited text | Parent state keyed by item id | Yes |
| Data shared across screens | Store or server cache keyed by id | Yes |
| Focus and scroll inside a row | Usually not preserved; see the accessibility chapter | No |
The rule is to key state by item id, never by index. State keyed by index has the same prepend problem as index keys.
A complete example: expandable rows
This component keeps the expanded set in the parent, uses getItemKey, and memoizes the row. The row's height changes when expanded, so it uses measureElement.
import { memo, useCallback, useRef, useState } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
type Item = { id: string; title: string };
type RowProps = {
item: Item;
expanded: boolean;
onToggle: (id: string) => void;
};
const Row = memo(function Row({ item, expanded, onToggle }: RowProps) {
return (
<div style={{ padding: 8, borderBottom: "1px solid #ddd" }}>
<button onClick={() => onToggle(item.id)}>
{expanded ? "▾" : "▸"} {item.title}
</button>
{expanded && <p>Details for {item.title}. This text makes the row taller.</p>}
</div>
);
});
export function ExpandableList({ items }: { items: Item[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
const onToggle = useCallback((id: string) => {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(id)) {
next.delete(id);
} else {
next.add(id);
}
return next;
});
}, []);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 40,
overscan: 5,
getItemKey: (index) => items[index].id,
});
return (
<div ref={parentRef} style={{ height: 400, overflow: "auto" }}>
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
{virtualizer.getVirtualItems().map((v) => {
const item = items[v.index];
return (
<div
key={v.key}
data-index={v.index}
ref={virtualizer.measureElement}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${v.start}px)`,
}}
>
<Row item={item} expanded={expanded.has(item.id)} onToggle={onToggle} />
</div>
);
})}
</div>
</div>
);
}Scroll away from an expanded row and back. It is still expanded, because the state lives in the parent and is keyed by item.id. The virtualizer re-measures the row when it returns, so the height is correct.
Memoization: what actually re-renders
The virtualizer triggers a re-render of the list component whenever the visible range changes. In the hand-written list, setScrollTop runs on every scroll event, so the parent re-renders even when the range stays the same.
Without memoization, each of those renders re-renders every mounted row, though most are unchanged. React.memo skips a row when its props are shallowly equal to the previous props. That works only if the props are stable:
- Pass the
itemobject, not a freshly built copy such as{ ...item }. - Pass
expandedas a boolean, not the wholeSet. If you passed theSet, every toggle would re-render every row. - Wrap handlers in
useCallbackwith stable dependencies. Using the functional form ofsetExpandedis what keepsonTogglestable here. - Do not pass inline style objects or arrays as props to the memoized row. Pass primitives, such as
top, and build the style object inside the row.
In the hand-written list, the same idea looks like this:
import { memo } from "react";
type FixedRowProps = { label: string; top: number; height: number };
const FixedRow = memo(function FixedRow({ label, top, height }: FixedRowProps) {
return (
<div style={{ position: "absolute", top, left: 0, right: 0, height }}>
{label}
</div>
);
});The parent renders <FixedRow key={items[i].id} label={items[i].label} top={i * rowHeight} height={rowHeight} />. All four props are primitives, so a row whose index and data have not changed is skipped.
Memoization is not free
React.memo adds a prop comparison to every row on every render. For a cheap row, that comparison can cost about as much as rendering it. Memoize when the row is non-trivial: it has child components, formatting work, or images. Confirm the gain with the React Profiler, as covered in the measuring chapter. Check how many rows render per scroll tick, and how long the commit takes, before and after.
Also keep expensive derived values out of the row's render path. Compute formatted dates or filtered data once, in useMemo in the parent or in the data layer, not once per row per scroll event.
Common errors
- State bleeds between rows after inserting or sorting. The cause is index keys or index-keyed state. Switch to ids.
- Row heights look wrong after data changes. The measurement cache is keyed by index. Add
getItemKey. - Typed text vanishes on scroll. The input is uncontrolled and lives in the row. Store the value in parent state or a store, keyed by id.
React.memoseems to do nothing. A prop changes identity on every render, usually an inline function, object, or array. Log which prop differs, or use the Profiler's "why did this render" information.- Every row remounts on each scroll tick. The key is unstable, for example a random value or an array index combined with a changing offset.
Exercise
A chat list prepends new messages at index 0. Each row has a local useState for "show translation", and rows use key={index}. After a new message arrives, a different message appears translated. Why, and what are two changes that fix it?
Show answer
With index keys, React reuses the instance at index 0 for the new message, and that instance still holds the old message's "show translation" state. Fix it by using the message id as the key (and getItemKey if using TanStack Virtual). For state that must survive scrolling, also move it into parent state keyed by message id, because local state is lost when a row unmounts.
Exercise
You memoize Row with React.memo, but all rows still re-render whenever one row is expanded. The parent passes expanded={expandedSet} and onToggle={(id) => toggle(id)}. Name both problems and the fix for each.
Show answer
Passing the whole Set gives every row a new prop value after each toggle, so pass expanded={expandedSet.has(item.id)}, a boolean. The inline arrow function creates a new function on every render, so define the handler once with useCallback (using the functional setState form so it has no changing dependencies) and pass that.