Profiling Before Optimizing
You'll learn how to measure performance scientifically before applying useMemo or useCallback.
Why Measure First?
The golden rule of optimization is: don't guess, measure. You might think a calculation is slow, but intuition is unreliable. Memoization adds complexity and memory overhead—if the computation you're optimizing takes 0.1 milliseconds, caching it wastes more resources than it saves.
Think of it like buying a faster microwave because you heat one cup of coffee per day. The purchase cost (complexity) far exceeds the time saved.
Using React DevTools Profiler
The Profiler tab in React DevTools records component render times:
- Open DevTools → Profiler tab
- Click the record button
- Interact with your app
- Stop recording and examine the flame graph
Look at the "Render duration" for specific components. If a component consistently takes 10-20ms or more to render, investigate what's happening inside it.
Using console.time() for Precision
To measure a specific computation:
function ExpensiveComponent({ data }) {
console.time('heavy-calculation');
const result = data.map(/* complex transformation */);
console.timeEnd('heavy-calculation');
return <div>{result}</div>;
}
Check the browser console. If it logs "heavy-calculation: 0.2ms", memoization won't help. If it logs "heavy-calculation: 50ms", now you have evidence that useMemo makes sense.
The Evidence-Based Approach
Profile → identify bottleneck → optimize → profile again to verify. Without the first step, you're optimizing blindly and often making things worse.
Key Takeaway: Always use React DevTools Profiler or console.time() to prove a computation is actually slow before adding useMemo or useCallback—premature optimization adds complexity without benefit.