CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

App.jsx
import { useMemo } from "react";

// Write the Stats component here

Sample solution

App.jsx
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;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What must useMemo's function be?

  • useEffect
  • Async
  • DOM mutation
  • Pure Correct answer

Explanation: useMemo's function must be pure.

2 Overhead

Question
Wrapping small computations in useMemo adds ____.
Answer
Wrapping small computations in useMemo adds overhead.

Explanation: Small computations add overhead.

3 Match the useMemo pitfalls

Term Meaning
small compute overhead
side effect forbidden
missing deps stale
pure required

All lessons in Intermediate