The useMemo Hook and Expensive Computations
The useMemo Hook and Expensive Computations
1. What is useMemo?
While useCallback caches a function definition, useMemo caches the result of an expensive computation.
$$\text{CachedResult} = \text{useMemo}(\text{calculateValue}, \text{dependencies})$$
On initial render, useMemo calls your calculation function and stores the result. On subsequent renders, React checks if the dependencies have changed:
- If dependencies are unchanged, React returns the cached result without running the calculation again.
- If dependencies have changed, React re-executes the calculation, stores the new result, and returns it.
2. Practical Example: Filtering 10,000 Complex Records
3. Difference Between useMemo and useCallback
Engineers often confuse the two hooks:
useMemo: Invokes the function and caches its return value (useMemo(() => computeVal(), deps)).useCallback: Caches the function itself without executing it (useCallback(() => doSomething(), deps)).
In fact, useCallback(fn, deps) is simply syntactic sugar for:
4. When Is a Calculation Truly "Expensive"?
Most everyday JavaScript operations (mapping 50 array elements, basic math, string concatenations) execute in fractions of a microsecond. Wrapping them in useMemo adds more overhead than it saves!
How to measure:
Use console.time() or the React DevTools Profiler:
If the calculation takes less than 1ms, memoization is unnecessary. If it takes 10ms or more, wrapping it in useMemo delivers substantial real-world responsiveness gains.
Practice Quiz
useMemo hook cache across component renders?useMemo differ from useCallback?useMemo genuinely justified?useMemo(() => computeTotal(items), [items]) has an unchanged items array, what does React do during render?useCallback(fn, deps) expressed using useMemo?Extracting Reusable Business Logic into Custom Hooks
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| The useCallback Hook and Stabilizing Callback Props | Extracting Reusable Business Logic into Custom Hooks |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.