useMemo
useMemo caches the calculated result of an expensive calculation between renders until dependencies change.
Mental Model
"The Calculator Memory: Instead of recalculating a 50-digit equation every time, you store the final answer in the calculator memory."
Interactive Engine Walkthrough
Invariant:The stability of this sequence is what allows React to persist state across asynchronous render cycles.
Reference Code Snippet
1function Analytics({ data, filter }) {
2 // Only re-calculate if 'data' or 'filter' changes
3 const computed = useMemo(() => {
4 return expensiveCalculation(data, filter);
5 }, [data, filter]);
6
7 return <div>Result: {computed}</div>;
8}- 01.Only use useMemo for truly computationally expensive operations or preserving reference equality for props.
- 02.useMemo runs during rendering, so avoid side effects inside the calculation function.
- 03.Overusing useMemo on trivial calculations adds memory overhead without performance benefits.
01. Computational Memoization
`useMemo` caches the **result** of a calculation between re-renders. If the dependencies haven't changed, React skips the expensive function and returns the value it stored in memory from the last run.
Optimization Flow
02. The Cost of Caching
Many developers over-use `useMemo`. Memoization isn't free—React has to compare the dependencies and store the values in memory. For simple arithmetic or array filters, the cost of `useMemo` might be higher than just re-running the calculation.
Performance Audit
"Use 'useMemo' only for truly expensive operations (complex sorting, heavy data processing) or to maintain stable object references when passing props to memoized children."