easyReact Native#19

Memoize callbacks with useCallback

Prompt

Create a list of items where each item has a "delete" button. Use useCallback to memoize the delete handler so it doesn't recreate on every render. Pass the handler as a prop to a child component wrapped in React.memo.

Solution

const MemoListItem = React.memo(ListItem)
const handleDelete = useCallback((id) => {
  setItems(prev => prev.filter(i => i.id !== id))
}, [])
return (
  <View>
    {items.map(item => <MemoListItem key={item.id} item={item} onDelete={handleDelete} />)}
  </View>
)
Mentor's take

useCallback is about identity, not speed. An inline arrow is a new function object every render; React.memo's shallow comparison sees a new onDelete prop and re-renders every row — the memo becomes pure overhead. useCallback returns the same function reference across renders, which is what lets the memoized rows actually bail out. The function still gets allocated each render (the arrow is an argument to useCallback); what you're buying is the stable reference handed to children.

The empty deps array is only legal because of the functional update: setItems(prev => prev.filter(...)) reads the freshest state at apply time, so the handler needs nothing from closure scope. Write setItems(items.filter(...)) instead and you're forced to add items to deps — new identity on every list change, memo defeated, back to square one. Functional updates and useCallback([]) are a paired idiom.

Per-row memoization is the highest-leverage place for this pattern in RN: deleting one item should re-render one component's removal, not every surviving row, and in long lists that difference is measurable JS-thread time.

Red flag: useCallback sprinkled on handlers whose children aren't memoized — stable identity nobody consumes is pure ceremony. The pattern is a pair: stable callback plus memoized consumer.

Say it: "useCallback buys referential stability, not speed — it only pays when a memoized child consumes it, and functional setState is what lets the deps array stay empty."