React
Pitfalls
Learn the cost of overusing useMemo.
Pitfalls
Misusing useMemo can hurt code. Three common mistakes: wrapping small computations (added overhead), calling functions with side effects (useMemo must be pure), forgetting dependencies.
For small computations, React's own speed is enough. A line like const sum = useMemo(() => a + b, [a, b]) may be slower than const sum = a + b due to caching overhead.
useMemo's function must be pure: no API calls, no DOM mutations, no setState. Side effects belong in useEffect. A missing dependency array makes useMemo return stale values and cause bugs.
Stale value
If useMemo's dependency array is missing, it returns a stale value. This is called stale closure. For example, useMemo(() => compute(count), []) always computes with the initial count; current count isn't used.
This bug is caught by lint rules: the react-hooks/exhaustive-deps rule warns about missing deps. So adding eslint-plugin-react-hooks is a good habit.
Sometimes you intentionally skip a dependency (when you want only the initial value). In that case, adding // eslint-disable-next-line signals intent. But it's rare.
Exercise Sum and average
Complete the skeleton. Write a Stats component. Take ({ '{ numbers }' }). Compute stats with useMemo(() => { '{ const sum = numbers.reduce((a, b) => a + b, 0); return { '{ sum, avg: sum / numbers.length }' }; }' }, [numbers]). Show <p>{ '{ stats.sum }' } / { '{ stats.avg }' }</p>. Export it.
Show example solution
import { useMemo } from "react";
function Stats({ numbers }) {
const stats = useMemo(() => {
const sum = numbers.reduce((a, b) => a + b, 0);
return { sum, avg: sum / numbers.length };
}, [numbers]);
return <p>{stats.sum} / {stats.avg}.</p>;
}
export default Stats;
Test yourself
-
What must useMemo's function be?
- useEffect
- Async
- DOM mutation
- Pure
Show answer
Pure — useMemo's function must be pure.
-
Overhead
Wrapping small computations in useMemo adds ____.
Show answer
Wrapping small computations in useMemo adds overhead.
-
Match the useMemo pitfalls
- small compute
- overhead
- side effect
- forbidden
- missing deps
- stale
- pure
- required
Next lesson: Summary - useMemo