| Identify Unnecessary React Re-renders :👈 | 👉:Optimize Large React List |
React.memo vs useMemo vs useCallback |
React.memo vs useMemo vs useCallback
1. Introduction
React provides three commonly used performance optimization tools:
- React.memo: Prevents a component from re-rendering when its props have not changed.
- useMemo: Memoizes the result of a calculation so React can reuse it between renders.
- useCallback: Memoizes a function reference so React can reuse the same function between renders.
All three help avoid unnecessary work, but they operate at different levels.
2. React.memo
What is React.memo?
React.memo is a higher-order component that memoizes a component.
It prevents a component from re-rendering when its props are unchanged, using a shallow comparison by default.
Example: Without React.memo
function UserDetails({ name }) {
console.log("UserDetails rendered");
return <h3>User: {name}</h3>;
}
function App() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<UserDetails name="John" />
</>
);
}
What happens?
- When the button is clicked, the count state changes.
- The App component re-renders.
- UserDetails also re-renders, even though its name prop has not changed.
const UserDetails = React.memo(function UserDetails({ name }) {
console.log("UserDetails rendered");
return <h3>User: {name}</h3>;
});
function App() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<UserDetails name="John" />
</>
);
}
What happens now?
- When count changes, App re-renders.
- React compares the previous and new props of UserDetails.
- Since name remains "John", UserDetails normally skips re-rendering.
- React.memo compares props, not the component's own state.
- A component can still re-render when its own state changes.
- It can also re-render when a Context it consumes changes.
- By default, React compares each prop using Object.is.
- You can provide a custom comparison function as the second argument, but it should be used carefully.
3. useMemo
What is useMemo?
useMemo is a React Hook that memoizes the result of a calculation.
React recalculates the value when one of its dependencies changes. Otherwise, it can reuse the previously calculated value.
Syntax:
const memoizedValue = useMemo(() => {
return expensiveCalculation();
}, [dependencies]);
Example: Without useMemo
function ProductList({ products }) {
const [count, setCount] = useState(0);
const expensiveProducts = products.filter(product => {
console.log("Filtering products");
return product.price > 1000;
});
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
{expensiveProducts.map(product => (
<p key={product.id}>{product.name}</p>
))}
</>
);
}
Problem:
- Every time count changes, ProductList re-renders.
- The filter operation runs again, even though products have not changed.
- This can waste time when the calculation is expensive or the collection is large.
function ProductList({ products }) {
const [count, setCount] = useState(0);
const expensiveProducts = useMemo(() => {
console.log("Filtering products");
return products.filter(product =>
product.price > 1000
);
}, [products]);
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
{expensiveProducts.map(product => (
<p key={product.id}>{product.name}</p>
))}
</>
);
}
What happens now?
- When count changes, ProductList re-renders.
- React checks whether products has changed.
- If products has not changed, React reuses the previous filtered result.
- The filtering operation runs again only when the products dependency changes.
- useMemo memoizes a calculated value, not a component or function reference.
- All reactive values used in the calculation should be included in the dependency array.
- It is useful for expensive calculations and preserving object or array references.
- Do not use it for every calculation. Memoization also has a cost.
4. useCallback
What is useCallback?useCallback is a React Hook that memoizes a function reference.
It returns the same function reference between renders as long as its dependencies have not changed.
Syntax:
const memoizedFunction = useCallback(() => {
// Function logic
}, [dependencies]);
Example: Without useCallback
const UserDetails = React.memo(function UserDetails({ onSave }) {
console.log("UserDetails rendered");
return (
<button onClick={onSave}>
Save User
</button>
);
});
function App() {
const [count, setCount] = useState(0);
const handleSave = () => {
console.log("User saved");
};
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<UserDetails onSave={handleSave} />
</>
);
}
Problem:
- Every time App renders, a new handleSave function is created.
- The function reference changes even though its logic is the same.
- React.memo detects that onSave has changed.
- As a result, UserDetails re-renders unnecessarily.
const UserDetails = React.memo(function UserDetails({ onSave }) {
console.log("UserDetails rendered");
return (
<button onClick={onSave}>
Save User
</button>
);
});
function App() {
const [count, setCount] = useState(0);
const handleSave = useCallback(() => {
console.log("User saved");
}, []);
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<UserDetails onSave={handleSave} />
</>
);
}
What happens now?
- React re-renders App when count changes.
- useCallback returns the same handleSave function reference because its dependencies have not changed.
- React.memo sees that the onSave prop is unchanged.
- UserDetails can skip its unnecessary re-render.
- useCallback memoizes a function reference, not the result of executing that function.
- Include all reactive values used inside the callback in its dependency array.
- When a dependency changes, React returns a new function reference.
- It is especially useful when passing callbacks to memoized child components or using functions as Hook dependencies.
5. Main Differences: React.memo vs useMemo vs useCallback
| Feature | React.memo | useMemo | useCallback |
|---|---|---|---|
| Type | Higher-order component | React Hook | React Hook |
| Purpose | Skip unnecessary component re-renders when props are unchanged | Reuse a calculated value | Reuse a function reference |
| What is memoized? | Component rendering based on props | Calculation result | Function reference |
| Where is it used? | When defining a component | Inside a component or custom Hook | Inside a component or custom Hook |
| Dependency array | No | Yes | Yes |
| Common use case | Prevent unnecessary child component renders | Expensive calculations | Stable callback references |
| Example | React.memo(MyComponent) | useMemo(() => calculate(), [value]) | useCallback(() => save(), [value]) |
6. Difference Between useMemo and useCallback
Both are similar because they memoize something based on dependencies.
The key difference is what they return.
useMemo returns a value:
const total = useMemo(() => {
return price * quantity;
}, [price, quantity]);
useCallback returns a function:
const calculateTotal = useCallback(() => {
return price * quantity;
}, [price, quantity]);
Remember this simple rule:
- useMemo: Memoize the result.
- useCallback: Memoize the function.
Conceptually, useCallback(fn, dependencies) is similar to useMemo(() => fn, dependencies).
7. Can We Use All Three Together?
Yes. They can work together when a component has expensive calculations and passes calculated values and callbacks to memoized child components. Example:
const ProductDetails = React.memo(function ProductDetails({
product,
onAddToCart
}) {
console.log("ProductDetails rendered");
return (
<div>
<h3>{product.name}</h3>
<p>Price: {product.price}</p>
<button onClick={onAddToCart}>
Add to Cart
</button>
</div>
);
});
function App() {
const [count, setCount] = useState(0);
const [quantity, setQuantity] = useState(1);
const product = useMemo(() => {
return {
id: 1,
name: "Laptop",
price: 50000
};
}, []);
const totalPrice = useMemo(() => {
return product.price * quantity;
}, [product, quantity]);
const handleAddToCart = useCallback(() => {
console.log("Added to cart:", product.name);
}, [product]);
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<button onClick={() => setQuantity(quantity + 1)}>
Increase Quantity
</button>
<p>Total Price: {totalPrice}</p>
<ProductDetails
product={product}
onAddToCart={handleAddToCart}
/>
</>
);
}
How do they work together?
- React.memo: Prevents ProductDetails from re-rendering when its props remain unchanged.
- useMemo: Keeps the product object reference stable and memoizes the total price calculation.
- useCallback: Keeps the handleAddToCart function reference stable.
When count changes, ProductDetails can skip rendering because its props remain unchanged. When quantity changes, totalPrice is recalculated, but ProductDetails can still skip rendering because the product and callback props remain unchanged.
8. When Should You Use Each One?
| Situation | Recommended approach |
|---|---|
| A child component re-renders even though its props have not changed. | React.memo |
| An expensive calculation runs on every render. | useMemo |
| A function is passed to a memoized child component. | useCallback |
| An object or array is recreated and passed to a memoized child. | useMemo |
| A function is used as a dependency of another Hook. | useCallback, when a stable reference is needed |
| A component is inexpensive and renders quickly. | Usually none of them |
9. Common Mistakes to Avoid
1. Using React.memo without stable props
<UserDetails user={{ name: "John" }} />
A new object is created on every parent render. React.memo detects a changed prop reference.
Better approach:
const user = useMemo(() => ({
name: "John"
}), []);
return <UserDetails user={user} />;
2. Using useCallback for every function Not every function needs memoization. If the function is not passed to a memoized child or used in a dependency-sensitive Hook, useCallback may provide no meaningful benefit.
3. Using useMemo for simple calculationsconst total = useMemo(() => price + tax, [price, tax]);
For a simple addition, ordinary calculation is usually better:
const total = price + tax;
4. Forgetting dependencies
Incorrect:
const handleSave = useCallback(() => {
console.log(userName);
}, []);
The callback can retain an outdated userName value.
Correct:
const handleSave = useCallback(() => {
console.log(userName);
}, [userName]);
5. Expecting React.memo to prevent every re-render React.memo only helps with re-renders caused by unchanged props. A component may still render because of its own state, consumed Context, or other React updates.
6. Using memoization as a substitute for good component design Sometimes moving state closer to the component that needs it, splitting large components, or avoiding unnecessary Context updates is a better solution than adding memoization everywhere.
10. Important React Version Consideration
React Compiler can automatically optimize many components, values, and function references when it is enabled and configured for the project. With React Compiler, manual use of React.memo, useMemo, and useCallback is often less necessary. However, understanding them remains important for maintaining existing applications and working with projects that do not use the compiler. Also, memoization is a performance optimization, not a guarantee of permanent caching. React may discard memoized values in certain situations, so application correctness should not depend on memoization.
11. Interview Questions and Answers
Q1. What is the difference between React.memo and useMemo? React.memo memoizes a component to skip rendering when its props are unchanged. useMemo memoizes the result of a calculation inside a component.
Q2. What is the difference between useMemo and useCallback? useMemo returns a memoized value, whereas useCallback returns a memoized function reference.
Q3. Does React.memo prevent a component from rendering when its state changes? No. React.memo compares props. The component can still re-render when its own state changes or its consumed Context changes.
Q4. Why do we use useCallback with React.memo? When a parent passes a function to a memoized child, a newly created function reference can cause the child to re-render. useCallback can preserve the reference while dependencies remain unchanged.
Q5. Does useMemo guarantee that a calculation runs only once? No. It reuses the previous result while dependencies remain unchanged, but React may discard the cached value in certain situations. It should be treated as a performance optimization.
Q6. Can useCallback replace useMemo? No. They have different purposes. useCallback memoizes a function reference, while useMemo memoizes a calculated value.
Q7. What happens if we forget the dependency array? For useMemo and useCallback, omitting the dependency array means the calculation or function is recreated on every render. An empty dependency array means there are no reactive dependencies, so React can reuse the cached result or function between renders.
Q8. Should we use React.memo for every component? No. Memoization has its own overhead. Use it when profiling shows that avoiding a component render provides a meaningful performance improvement.
12. Quick Summary
- React.memo: Optimizes component rendering based on props.
- useMemo: Optimizes expensive calculations by memoizing their results.
- useCallback: Optimizes function references by memoizing callbacks.
| React feature | Remember it as |
|---|---|
| React.memo | Memoize a component |
| useMemo | Memoize a value |
| useCallback | Memoize a function |
| Identify Unnecessary React Re-renders :👈 | 👉:Optimize Large React List |
Comments and Discussion