Measuring Expensive Computations
You'll learn: How to determine if a calculation is actually slow enough to warrant useMemo optimization.
The Problem with Guessing
Not all computations are expensive. Wrapping everything in useMemo adds overhead—the hook itself has a cost. You need data, not intuition, to decide if memoization is worth it.
How to Measure
The simplest approach: time it manually using console.time():
function ExpensiveList({ items }) {
console.time('filterAndSort');
const processed = items
.filter(item => item.active)
.sort((a, b) => a.priority - b.priority);
console.timeEnd('filterAndSort');
return <ul>{/* render */}</ul>;
}
Run this and check your browser console. You'll see timing like filterAndSort: 0.2ms or filterAndSort: 45ms.
What's Actually "Expensive"?
Rough guidelines:
- < 1ms: Almost never worth memoizing
- 1-5ms: Probably fine, profile in context
- > 5ms: Consider
useMemoif it runs frequently
Remember: a 0.5ms computation that runs 100 times per render adds up differently than one that runs once.
Measuring in Real Scenarios
Profile during realistic interactions:
function DataTable({ rawData }) {
console.time('processData');
const processed = rawData.map(/* complex transform */);
console.timeEnd('processData');
// Check timing when rawData has 10, 100, 1000, 10000 items
}
Test with production-sized datasets. That cute demo data with 5 items won't reveal the real cost.
The React DevTools Approach
Use the Profiler to see if the computation's render time stands out in the flamegraph. If the component itself is fast (< 2ms total render), the computation probably isn't your bottleneck.
Key Takeaway: Measure computation time with console.time() and realistic data before adding useMemo—optimize based on evidence, not assumptions.