React useMemo Hook
🧠 React useMemo Hook
The useMemo Hook is used to memoize expensive computations in React, so they are recomputed only when dependencies change.
It helps optimize performance by avoiding unnecessary recalculations on every render.
🛠 Syntax
-
computeExpensiveValue– function that returns a value -
[a, b]– dependencies array -
memoizedValue– cached value returned from the function -
The function runs only if dependencies change
🧪 Example 1: Basic useMemo
✅ Without useMemo, expensiveCalculation would run on every render (even when typing in input).
✅ With useMemo, it runs only when count changes.
🧪 Example 2: Memoize Object/Array
-
doubledis recomputed only whennumberschanges. -
Prevents unnecessary recalculations.
🧠 Difference Between useMemo and useCallback
| Hook | What it memoizes | Returns |
|---|---|---|
useMemo |
Value/result of a function | Memoized value |
useCallback |
Function itself | Memoized function reference |
🎯 When to Use useMemo
-
Expensive calculations that slow down renders
-
Filtering, sorting, or mapping large arrays
-
Memoizing objects or arrays passed to child components (avoid re-renders)
-
Optimizing performance in combination with
React.memo
⚠️ Important Notes
-
Don’t overuse
useMemofor trivial calculations -
Always provide proper dependencies
-
Memoization saves performance only for heavy computations
🔹 Summary Table
| Feature | Description |
|---|---|
| Memoizes values | ✔ |
| Runs function only when dependencies change | ✔ |
| Optimizes performance | ✔ |
| Returns memoized value | ✔ |
| Use with expensive calculations | ✔ |
