Sub topic 10
Keys, Row State, and Memoization
This chapter assumes you know React function components, useState, and how keys work in ordinary lists. You have a working virtual list from the earlier chapters. Now you will look at what happens to each row's identity and state as rows enter and leave the DOM.
Rows are mounted and unmounted constantly
In a normal list, every row stays mounted. In a virtual list, a row mounts when it scrolls into the rendered range and unmounts when it leaves. React destroys the component's state on unmount. Anything a row kept in useState, such as a checked box, an expanded panel, or text typed into an input, is lost when the user scrolls away and back.
Choose stable keys
The hand-written list used key={i}, where i is the item's index. That works only while the list never changes. If the user sorts, filters, or prepends items, index 5 now refers to a different item. React reuses the old row's component and state for the new item, so a checked box can appear on the wrong row.
Use an ID from your data instead. With TanStack Virtual, pass getItemKey so that v.key is that ID and not the index:
import { useVirtualizer } from "@tanstack/react-virtual";
type Item = { id: string; label: string };
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
getItemKey: (index) => items[index].id,
});The same key also lets the virtualizer keep cached measurements attached to the right item when the order changes.
Keep state outside the row
Stable keys do not save state across unmounts. For state that must survive scrolling, store it above the virtualized list and pass it down. A Set of selected IDs in the parent works well.
import { useState } from "react";
type Item = { id: string; label: string };
export function SelectableList({ items }: { items: Item[] }) {
const [selected, setSelected] = useState<Set<string>>(new Set());
const toggle = (id: string) =>
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
return (
<ul>
{items.map((item) => (
<li key={item.id}>
<label>
<input
type="checkbox"
checked={selected.has(item.id)}
onChange={() => toggle(item.id)}
/>
{item.label}
</label>
</li>
))}
</ul>
);
}Here the list is shown unvirtualized for brevity. Put the same selected set and toggle function in the parent of your virtual list and pass them to each rendered row. The row becomes a pure function of its props, so remounting it costs nothing.
Memoize rows
Every scroll event updates scrollTop state, which re-renders the list component. Without memoization, every visible row re-renders on each update, even when its item has not changed. Wrap the row in React.memo so it re-renders only when its props change:
import { memo } from "react";
type RowProps = {
id: string;
label: string;
checked: boolean;
onToggle: (id: string) => void;
};
export const Row = memo(function Row({ id, label, checked, onToggle }: RowProps) {
return (
<label>
<input type="checkbox" checked={checked} onChange={() => onToggle(id)} />
{label}
</label>
);
});Memoization only helps if props stay referentially equal between renders. Watch for these common mistakes:
- Passing an inline callback such as
onToggle={() => toggle(item.id)}. It is a new function each render and defeatsmemo. Pass a stabletoggle(wrapped inuseCallbackif needed) and let the row call it with its ownid. - Passing a fresh style object per row. Compute positioning in the wrapper element, and keep it outside the memoized row.
- Passing the whole
selectedset to every row. Pass the booleancheckedinstead, so only the rows whose value changed re-render.
Exercise
A user ticks a checkbox in row 40, scrolls down 500 rows, then scrolls back. The checkbox is empty. The checked value was stored with useState inside the row component. What is the cause, and what is the fix?
Show answer
Row 40 unmounted when it left the rendered range, so React discarded its local state. Move the checked state into the parent as a set of selected item IDs, and pass a checked boolean and a stable toggle function to each row.
Exercise
Why does passing onToggle={() => toggle(item.id)} to a React.memo row defeat memoization, and what do you pass instead?
Show answer
The arrow function is a new object on every render, so the prop never compares equal and the row re-renders each time. Pass the stable toggle function and have the row call toggle(id) using its own id prop.