Hooksintermediate
useMemo for Expensive Computations
Learn how useMemo caches the result of an expensive calculation between renders to avoid redundant work.
useMemo(factory, deps) runs factory during render and caches (memoizes) its return value, only recomputing it when one of the values in deps changes between renders. On renders where dependencies haven't changed, React returns the previously cached value instead of re-invoking the factory function.
useMemo is like keeping a pre-baked batch of bread in the freezer instead of baking a fresh loaf every single time someone asks for toast — you only fire up the oven again when the recipe (dependencies) actually changes.
Key Concepts
1
This is primarily a performance optimization for computations that are genuinely expensive relative to a typical render — filtering or transforming large arrays, complex derived calculations, or building a large data structure. It is not needed for cheap operations, since the overhead of comparing dependencies can outweigh recomputing something trivial.
2
A second common use is preserving referential stability of derived objects or arrays so that they don't cause unnecessary re-renders in memoized child components (React.memo) or unnecessary effect re-runs in useEffect dependency arrays, since a freshly created object or array literal is a new reference every render even if its contents are equal.
React.memouseEffect
3
Interviewers often ask candidates to identify when useMemo is actually warranted versus premature optimization — the correct answer emphasizes profiling first, since useMemo itself has a small cost (storing the cached value and comparing dependencies) and indiscriminate use adds complexity without measurable benefit.
useMemo