CodeBlanks Logo Icon CodeBlanks

Summary - React.memo

Write a memoized list item and a useCallback parent.

Summary - React.memo

In this group you learned what React.memo is, prop comparison, and custom comparators. Now you can protect expensive components from needless renders.

The recipe: wrap big list items and expensive components with memo, stabilize function props with useCallback, stabilize object props with useMemo or module scope. Custom comparators are a last resort.

In the next step you'll write a big list example with memo'd list + useCallback.

Practice BigList memo + callback

Complete the skeleton. Write an App component. Define items with useState(["a","b","c"]). Define handleClick with useCallback((item) => console.log(item), []). Inside <ul>, render items.map((item, i) => <li key={ '{ i }' } onClick={ '{ () => handleClick(item) }' }>{ '{ item }' }</li>). Export it.

Starter code

App.jsx
import { useState, useCallback } from "react";

// Write the App component here

Sample solution

App.jsx
import { useState, useCallback } from "react";

function App() {
  const [items] = useState(["a", "b", "c"]);
  const handleClick = useCallback((item) => console.log(item), []);
  return (
    <ul>
      {items.map((item, i) => (
        <li key={i} onClick={() => handleClick(item)}>{item}</li>
      ))}
    </ul>
  );
}

export default App;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is React.memo's default comparison?

  • Shallow Correct answer
  • Deep
  • JSON.stringify
  • Ignores

Explanation: Default is shallow compare.

2 Match the React.memo recipe

Term Meaning
memo wrap
useCallback function
useMemo object
custom compare last resort

All lessons in Intermediate