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 Simulation
Invariant:The stability of this sequence is what allows React to persist state across asynchronous render cycles.
Executable 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.Component re-renders are triggered by state or prop changes.
- 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
- 03.Automatic batching optimizes multiple state updates into a single render cycle.
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."