HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptreactModeratepending

React useCallback and useMemo - When They Actually Help

Submitted by: @anonymous··
0
Viewed 0 times
useCallbackuseMemoReact.memomemoizationperformancepremature optimization

Problem

Developers wrap every function in useCallback and every value in useMemo 'for performance', but this often makes code slower and harder to read with no benefit.

Solution

Only memoize when there's a measurable benefit:

DO memoize when:
  1. Passing callbacks to memoized children (React.memo)
  2. Callback is a dependency of another hook (useEffect)
  3. Expensive computations (>1ms) that don't need to rerun every render



DON'T memoize when:
  1. The component is cheap to re-render anyway
  2. The memoized value changes every render (defeats the purpose)
  3. No child component is wrapped in React.memo



// UNNECESSARY - no memo'd children care about this
const handleClick = useCallback(() => {
  setCount(c => c + 1);
}, []);

// USEFUL - prevents ExpensiveList from re-rendering
const sortedItems = useMemo(
  () => items.sort((a, b) => a.name.localeCompare(b.name)),
  [items]
);
return <ExpensiveList items={sortedItems} />;
// where ExpensiveList is wrapped in React.memo


Profile first with React DevTools Profiler before adding memoization.

Why

useCallback and useMemo have overhead: storing previous values, comparing dependencies, and the cognitive cost of reading the code. This overhead must be justified by actual performance gains.

Gotchas

  • useMemo is not a semantic guarantee - React may drop cached values
  • Memoizing everything can actually increase memory pressure

Context

React performance optimization

Revisions (0)

No revisions yet.