React useMemo Hook
In React, functional components re-render whenever their state or props change. Sometimes, components perform expensive calculations on each render, which can hurt performance.
What is useMemo?
useMemo is a React hook that returns a memoized value, recalculating it only when one of its dependencies changes.
Syntax:
const memoizedValue = useMemo(() => {
// expensive calculation
return computedValue;
}, [dependencies]);
memoizedValue→ The cached value[dependencies]→ Variables that trigger recalculation when changed
Why Use useMemo?

- Optimize expensive calculations: Avoid recalculating the same value on every render.
- Improve performance: Especially in large component trees or complex computations.
- Prevent unnecessary re-renders: When used with
React.memofor child components.
Example:
import React, { useState, useMemo } from "react";
function App() {
const [count, setCount] = useState(0);
const [text, setText] = useState("");
// Expensive calculation
const factorial = useMemo(() => {
console.log("Calculating factorial...");
const calculateFactorial = n => {
return n <= 0 ? 1 : n * calculateFactorial(n - 1);
};
return calculateFactorial(count);
}, [count]); // Recalculate only when 'count' changes
return (
<div>
<h1>Factorial of {count}: {factorial}</h1>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<inputtype="text"
value={text}
onChange={e => setText(e.target.value)}
placeholder="Type something..."
/>
</div>
);
}
export default App;
- The factorial is recomputed only when
countchanges, even iftextchanges. - Without
useMemo, factorial would be recalculated every render, which is inefficient for expensive calculations.
useMemo vs useCallback
| Hook | Purpose | Returns |
|---|---|---|
| useMemo | Memoizes values from expensive calculations | Memoized value |
| useCallback | Memoizes functions to avoid re-creation | Memoized function |
- Use useMemo when you want to cache a computed value.
- Use useCallback when you want to cache a function reference.
