Lists, Keys & Reconciliation Performance
⚛ ری‌اکت

Lists, Keys & Reconciliation Performance

Stable keys, anti-patterns with index keys, and list virtualization basics.

BugCast Admin··۵ دقیقه مطالعه

Keys help React identify which items changed, were added, or removed. Wrong keys cause bugs and wasted DOM work — a staple interview topic.

Common Interview Questions

Q: Why are keys required in lists?

Answer: Keys give list items stable identity across renders so React can match old and new elements correctly during reconciliation.

Q: Why is index as key bad?

Answer: When order changes or items insert/delete, index keys misassociate component state and cause unnecessary DOM updates.


// Reorder [A,B,C] to [C,A,B] with index keys
// React reuses wrong component state for wrong items

Q: Where to put the key?

Answer: On the outermost element returned inside map, or on Fragment with key prop when returning multiple siblings (<Fragment key={id}>).

Q: When is virtualization needed?

Answer: Rendering thousands of DOM nodes tanks performance. Libraries like react-window render only visible rows plus overscan buffer.

Key Points for Interviews

  • Use stable unique IDs from data

  • Never generate random keys during render

  • Keys are hints, not global identifiers

  • Fragment shorthand <> cannot take a key

  • Virtualize long lists before micro-optimizing memo

#keys#lists#interview

مطالب مرتبط