What is useMemo?
The useMemo hook is a built-in React hook that lets you cache the result of a calculation between re-renders. It is primarily used for performance optimization by ensuring that expensive logic only runs when its dependencies change.
Basic Syntax
Expensive Calculation Example
Without useMemo, every time a component re-renders (even due to unrelated state changes), all logic inside the component body runs again. In the example below, filtering a large list is wrapped in useMemo to prevent lag when typing in an unrelated input field.
When to Use useMemo
- Expensive Calculations: When a function takes significant time to execute (e.g., processing thousands of data points).
- Referential Integrity: When passing objects or arrays as props to a memoized child component (
React.memo) to prevent unnecessary renders. - Dependency for other Hooks: When an object or array is a dependency for
useEffector anotheruseMemo.
Comparison: useMemo vs useCallback
| Feature | useMemo | useCallback |
|---|---|---|
| Returns | The result of the function (Value) | The function itself |
| Purpose | Cache a calculated value | Cache a function definition |
| Usage | const val = useMemo(() => compute(), [d]) | const fn = useCallback(() => compute(), [d]) |
Common Pitfalls
Best Practices
- Measure first: Only optimize if you notice performance issues.
- Keep it pure: The function inside
useMemoshould not have side effects. - Verify dependencies: Ensure all variables used inside the function are in the dependency array.
- Readability: Don't sacrifice clean code for micro-optimizations that don't impact the user.