The useMemo hook memoizes expensive computations to avoid recalculating on every render. Here's when and how to use it effectively.
Basic Usage#
Expensive Calculations#
Filtering and Sorting#
Derived State#
Object/Array Stability#
Complex Data Transformations#
Search Index#
Context Value Memoization#
Lazy Computation#
When NOT to Use useMemo#
Best Practices#
When to Use:
✓ Expensive calculations
✓ Complex data transformations
✓ Stable object/array references
✓ Context provider values
Indicators:
✓ Sorting/filtering large arrays
✓ Recursive calculations
✓ Parsing/formatting operations
✓ Building derived data structures
Performance:
✓ Profile before optimizing
✓ Keep dependency arrays minimal
✓ Consider computation cost vs memory
✓ Test with realistic data sizes
Avoid:
✗ Trivial calculations
✗ Primitive values
✗ Constantly changing dependencies
✗ Premature optimization
Conclusion#
useMemo memoizes expensive computations to avoid recalculating on every render. Use it for expensive operations like sorting large arrays, complex data transformations, or creating stable object references for memoized children. Avoid using it for cheap calculations where the memoization overhead exceeds the computation cost. Always profile first and optimize based on actual performance needs.