Expensive computation
- React course
- Intermediate
- Lesson 34/80
- 5 min
Wrap an expensive stats computation with useMemo.
Expensive computation
This lesson writes the StatsPanel component. It computes sum, average, and median from the numbers array. Cached with useMemo; no recompute while numbers don't change.
Median computation is expensive: sort the array, take the middle. For 1000 items, doing it every render is slow. useMemo reduces this load.
The panel computes once on each open; recomputes when numbers update. This gives a smooth user experience.
Three computations
The panel has three computations: sum, avg, median. All three are computed in a single useMemo as one object.
The pattern: const stats = useMemo(() => { const sum = ...; const avg = ...; const sorted = [...numbers].sort(...); const median = sorted[Math.floor(sorted.length / 2)]; return { '{ sum, avg, median }' }; }, [numbers]).
One useMemo keeps all computations together; all recompute when numbers change. This keeps consistency and code readable.
Practice Write StatsPanel
Complete the skeleton. Write a StatsPanel component. Take ({ '{ numbers }' }). Compute stats with useMemo(() => { const sum = numbers.reduce((a, b) => a + b, 0); const avg = sum / numbers.length; return { '{ sum, avg }' }; }, [numbers]). Show <p>{ '{ stats.sum }' } / { '{ stats.avg }' }</p>. Export it.
Starter code
import { useMemo } from "react";
// Write the StatsPanel component hereSample solution
import { useMemo } from "react";
function StatsPanel({ numbers }) {
const stats = useMemo(() => {
const sum = numbers.reduce((a, b) => a + b, 0);
const avg = sum / numbers.length;
return { sum, avg };
}, [numbers]);
return <p>{stats.sum} / {stats.avg}.</p>;
}
export default StatsPanel;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What should useMemo's dep be?
- useEffect
- useRef
- numbers Correct answer
- DOM
Explanation: The answer: numbers.
2 Median
To compute median, the array is first ____.
To compute median, the array is first sorted.
Explanation: Sorted first for median.
3 Match the expensive compute steps
| Term | Meaning |
|---|---|
useMemo |
cache |
numbers |
dep |
sort |
median |
reduce |
sum |