React’s useMemo
is a performance optimization hook. It helps your application avoid unnecessary re-computations by caching the result of a function based on its dependencies.
In simple terms:
useMemo
remembers the result of a calculation until its inputs change.
Why Use useMemo
?
React components re-render often. When they do, all functions run again, including ones that compute values.
Sometimes, these computations are:
- Heavy (slow or complex)
- Repeated unnecessarily
That’s where useMemo
helps. It caches the result and only re-computes when needed, making your app faster.
Basic Syntax
const memoizedValue = useMemo(() => computeFunction(a, b), [a, b]);
computeFunction(a, b)
: Your expensive function[a, b]
: Dependencies — re-run only when one of them changesmemoizedValue
: The cached result
Real Example
import React, { useMemo, useState } from 'react';
function App() {
const [count, setCount] = useState(0);
const [dark, setDark] = useState(false);
// Expensive calculation
const expensiveResult = useMemo(() => {
console.log("Calculating...");
let result = 0;
for (let i = 0; i < 1000000000; i++) {
result += count;
}
return result;
}, [count]);
const themeStyle = {
backgroundColor: dark ? "#333" : "#fff",
color: dark ? "#fff" : "#000"
};
return (
<div style={themeStyle}>
<h1>useMemo Example</h1>
<p>Expensive result: {expensiveResult}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setDark(!dark)}>Toggle Theme</button>
</div>
);
}
Without useMemo
Every time the theme changes, the expensive calculation re-runs, even though count
didn’t change. That’s slow.
With useMemo
Now, the calculation runs only when count
changes — not when the theme changes. Much faster!
When Should You Use useMemo
?
Use it when:
- You have expensive computations
- The computed value doesn’t change often
- You want to avoid unnecessary re-renders
Avoid overusing useMemo
. It adds complexity and might slow things down if used everywhere. Use it only where it clearly improves performance.
Common Mistakes to Avoid
- Using it for simple calculations
- Don’t memoize cheap values — it’s not worth it.
- Leaving the dependency array empty or incorrect
- Wrong dependencies can lead to stale or incorrect results.
- Confusing with
useCallback
useMemo
caches values.useCallback
caches functions.
Summary
useMemo
improves performance by caching calculated values.- It only re-runs the function if dependencies change.
- Use it for heavy or slow operations.
- Be cautious and don’t over-optimize.
Example use cases:
- Filtering a large list
- Sorting complex data
- Expensive math or API data parsing
With useMemo
, React apps become faster and more efficient — when used correctly.