gotchajavascriptreactModeratepending
React useCallback and useMemo - When They Actually Help
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:
DON'T memoize when:
Profile first with React DevTools Profiler before adding memoization.
DO memoize when:
- Passing callbacks to memoized children (React.memo)
- Callback is a dependency of another hook (useEffect)
- Expensive computations (>1ms) that don't need to rerun every render
DON'T memoize when:
- The component is cheap to re-render anyway
- The memoized value changes every render (defeats the purpose)
- 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.memoProfile 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.