Overview
TheuseMemo hook memoizes the result of an expensive calculation, recomputing it only when dependencies change. This is a performance optimization to avoid expensive calculations on every render.
Signature
Parameters
A function that computes and returns the value to be memoized. This function is called during rendering.Signature:
() => anyAn optional dependency array. The factory function re-runs only when one of the dependencies has changed.
- Omit or
null- Recalculate on every render - Empty array
[]- Calculate only once on mount - Array with values - Recalculate when any value changes
Returns
The memoized value returned by the factory function. On subsequent renders, returns the cached value unless dependencies have changed.
Usage Examples
Expensive Calculation
Complex Computation
Referential Equality
UseuseMemo to maintain referential equality for objects/arrays passed as props:
Memoizing Search Results
Sorting and Filtering
Computing Derived State
When to Use useMemo
Good Use Cases:
- Expensive calculations that take noticeable time
- Filtering or transforming large arrays
- Complex object transformations
- Maintaining referential equality for dependency arrays
- Computing derived values from props or state
Don’t Use When:
- The calculation is cheap (simple arithmetic, string concatenation)
- The value is used only once in the component
- Premature optimization without measuring performance
Rules and Behavior
- Synchronous execution - The factory function runs during render, not after
- Dependency comparison - Uses strict equality (
!==) to compare each dependency - No guaranteed caching - GlyphUI may discard cached values in the future (though current implementation persists them)
- Must be called at top level - Don’t call
useMemoinside loops, conditions, or nested functions - Only in functional components - Cannot be used in class components
- Pure function - The factory should be a pure function with no side effects
Dependency Array Behavior
| Dependencies | When Factory Runs |
|---|---|
Not provided or null | Every render |
[] | Once on mount only |
[a, b] | When a or b changes |
Implementation Details
- Factory function is called during component render (synchronous)
- Dependencies are compared using strict equality (
!==) - Cached value is stored in the component’s hooks data
- Recalculates if dependencies array changes in length or any value changes
- Errors in factory function are caught and logged; returns
undefinedon error - If no dependencies provided, recalculates on every render