Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 16.3 — memo: Skipping a Component's Render
React · Example 2 of 2

A custom comparator

The comparator returns true ("equal, skip") when x and y match, so a new point object with the same numbers doesn't render Marker. If Marker also took an onClick, the comparator would have to compare it too.

memo(Component) makes React skip rendering a component when its parent re-renders with props that are shallowly equal to last time; it breaks when you pass new objects, arrays or functions on every render, and it's worth it only for components that are slow to render or render very often.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

A <Chart data={data} /> is memoised but renders on every keystroke in a search box in the same parent. data is computed as const data = rows.map(toPoint). Fix it.

02

Write a memo comparator for <Avatar user={user} size={size} /> that skips rendering when the user's id and photoUrl and the size are unchanged.

Explain it without notes

01

What does memo do, exactly?

02

Why can a memo component still render on every parent render?

03

When would you write a custom comparator, and what are the risks?

04

How do you decide whether a component should be wrapped in memo?

A custom comparator

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

App rendered
  Marker rendered at 1,5
--- tick (new object, same x and y)
App rendered
--- move (x changes)
App rendered
  Marker rendered at 2,5