Profiling & Optimization — Series 2

Preview — 3 of 10 questions

javascript
const UserCard = React.memo(
  function UserCard({ user }) {
    return <div>{user.name}</div>;
  },
  (prevProps, nextProps) => prevProps.user.id === nextProps.user.id,
);
AIt's a custom equality function that overrides the default shallow prop comparison — returning true means "props are equal, skip the re-render." The risk here: if user.name changes but user.id stays the same, UserCard will incorrectly skip re-rendering and display stale data
BIt has no effect — React.memo only ever accepts a single argument
CIt runs before every render regardless of memoization, adding overhead with no actual benefit
DIt replaces shouldComponentUpdate entirely and is required on every class component

Why is using the array index as key risky here, if items can be reordered, inserted into, or have entries removed?

javascript
function List({ items }) {
  return (
    <ul>
      {items.map((item, index) => (
        <ListItem key={index} text={item.text} />
      ))}
    </ul>
  );
}
AReact throws a runtime error whenever index is used as a key
BWhen items are reordered, inserted, or removed, the index-to-item mapping shifts — so React may match an existing DOM node (and any internal state it holds, like an uncontrolled input's typed value) with a different logical item than before, since key is precisely what React uses to decide "is this the same item across renders?" This causes visual glitches or state bleeding between rows
CUsing index as a key is always wrong, even for a fully static list that never reorders, inserts, or removes items
DIndex keys only cause problems in React's legacy (pre-16) rendering mode — this isn't an issue in React 18+

javascript
// Rendering 10,000 rows directly
function BigList({ items }) {
  return <div>{items.map(item => <Row key={item.id} {...item} />)}</div>;
}
AReact automatically virtualizes any list rendering over 1,000 items — no extra work is needed here
BUsing key={item.id} instead of key={index} is the real fix — the current code's actual problem is the choice of key, not the number of rendered rows
CAll 10,000 Row components get mounted into the DOM at once, even though only a small visible slice is ever on screen — wasting memory and slowing both the initial render and any subsequent re-render; virtualization ("windowing," as done by libraries like react-window) only renders the rows currently within (plus a small buffer around) the visible viewport, recycling DOM nodes as the user scrolls
DThis is purely a network-bandwidth problem, not a rendering one — pagination is the only real fix

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.