Memoizing Component Lists with Map Callbacks
You'll learn how to optimize rendered lists by combining React.memo on list item components with useCallback for the mapping function and event handlers passed as props.
The List Rendering Challenge
When you render lists with .map(), each item typically receives callbacks as props (like onClick or onDelete). Without memoization, these callbacks are recreated on every parent render, causing every memoized list item to re-render anyway because the function references change.
The solution is a two-part optimization: wrap the list item component in React.memo AND stabilize the callbacks you pass to each item using useCallback.
The Pattern
For list items to truly skip re-renders, you need stable props. This means:
- Memoize the item component with
React.memoso it can bail out - Memoize the mapping callback if you create items inline
- Memoize event handlers passed to each item using
useCallback - Use functional updates or
useRefin those handlers to avoid dependencies that change
The trickiest part is the event handler: if you create a new function for each item (like onClick={() => handleDelete(item.id)}), you're creating unique references. Instead, create one stable handleDelete with useCallback that accepts the ID as a parameter.
The Mental Model
Think of it like a factory assembly line: React.memo is the quality inspector that decides if an item needs rebuilding. But if you hand the inspector a "blueprint" (callback function) that looks different every time—even if it does the same thing—they'll rebuild anyway. useCallback gives you the same blueprint reference each time.
Key Takeaway: For React.memo to work on list items, combine it with useCallback for all function props—especially event handlers that reference item-specific data. Otherwise, changing function references defeat the memoization.