Advanced Patterns — Series 3

Preview — 3 of 10 questions

One of these useMemo calls is worthwhile and one is noise. Which, and why?

javascript
function Chart({ points }) {
  const sorted = useMemo(() => [...points].sort((a, b) => a.x - b.x), [points]);
  const total = useMemo(() => points.length, [points]);
  return <Canvas data={sorted} count={total} />;
}
AThe sorted memo is worthwhile: sorting is O(n log n) and it produces a new array reference each render, which would otherwise force Canvas (if memoized) to re-render and re-run its own work. total is points.length — a primitive, trivially cheap to compute — so memoizing it adds hook overhead for no benefit
Btotal is the worthwhile one; primitives always need memoization
CBoth are essential
DNeither does anything because points changes every render anyway

Does useCallback here stop Toolbar from re-rendering on each keystroke?

javascript
function Toolbar({ onSave }) {  // NOT wrapped in React.memo
  return <button onClick={onSave}>Save</button>;
}

function Editor() {
  const [text, setText] = useState('');
  const handleSave = useCallback(() => save(text), [text]);
  return <><textarea value={text} onChange={e => setText(e.target.value)} /><Toolbar onSave={handleSave} /></>;
}
AYes — useCallback always prevents child re-renders
BYes, but only because handleSave depends on text
CNo. Toolbar is not wrapped in React.memo, so it re-renders whenever Editor re-renders regardless of prop identity. And even if it were memoized, handleSave's dependency is text, so its reference changes every keystroke anyway. useCallback only helps when the consumer does a referential check and the deps are stable
DNo, because useCallback is deprecated

In React 17+, clicking the button — does the native document listener still fire despite e.stopPropagation()?

javascript
document.addEventListener('click', () => console.log('native document click'));

function App() {
  return <button onClick={(e) => { e.stopPropagation(); console.log('react click'); }}>Go</button>;
}
ANo — stopPropagation on the synthetic event stops all listeners everywhere
BYes — React 17+ attaches its event listeners to the root DOM container (the element passed to createRoot), not document. e.stopPropagation() stops propagation within React's synthetic system and up to that root, but a listener on document (an ancestor of the root) still receives the event as it continues bubbling in the real DOM
CIt depends on the browser
DReact does not use event delegation at all

Sign up free to play

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