React · Lesson 11 of 15 · 5 min
Performance Optimization with Memoization
This is how you prove you understand React's render cycle and can fix real-world performance issues.
After this lesson, you'll know when to use React.memo, useMemo, and useCallback—and how to explain the trade-offs in an interview. You'll stop guessing and start profiling.
When to reach for memoization (and when not to)
React re-renders a component when its state or props change. By default, this also re-renders all its children. This is usually fast enough. Don't optimize what isn't slow.
You have a performance problem when a render takes too long, dropping your frame rate below 60fps. That gives you about 16ms per frame. The two most common culprits are:
- Expensive calculations running on every render (e.g., filtering a large array).
- A deep component tree where a state change at the top causes a cascade of unnecessary re-renders below.
Memoization is a cache. You trade a small amount of memory and the CPU cost of a comparison to skip doing expensive work again.
The trap: Premature optimization. Don't wrap every component in React.memo. Use the React DevTools Profiler to find the actual bottleneck. If a component renders in 1ms, optimizing it is a waste of time. Focus on the slow parts.
Fix expensive re-renders with React.memo and useCallback
The most common scenario is a pure component that re-renders only because its parent did. React.memo is a higher-order component that prevents this. It shallowly compares the component's props, and if they haven't changed, it skips the re-render.
This sounds easy, but it's defeated by referential equality. In JavaScript, {} === {} and () => {} === () => {} are both false. If you pass a new object or function to a memoized child on every render, its props are always "new," and it will always re-render.
This is where useCallback comes in. It memoizes a function instance.
useCallback gives you the exact same function reference on subsequent renders, as long as its dependencies haven't changed. This allows React.memo's shallow prop comparison to work correctly for callbacks.
import React, { useState, useCallback, memo } from 'react';
// --- Memoized Child Component ---
interface ProductCardProps {
productName: string;
onAddToCart: () => void;
}
const ProductCard = memo(({ productName, onAddToCart }: ProductCardProps) => {
console.log(`ProductCard for "${productName}" rendered`);
return (
<div style={{ border: '1px solid #ccc', padding: '10px', margin: '5px' }}>
<h4>{productName}</h4>
<button onClick={onAddToCart}>Add to Cart</button>
</div>
);
});
// --- Parent Component ---
function ProductList() {
const [cartCount, setCartCount] = useState(0);
const [products] = useState(['Laptop', 'Mouse', 'Keyboard']);
console.log('ProductList rendered');
// 1. useCallback for a stable event handler reference
const handleAddToCart = useCallback(() => {
// This function will be the same instance across re-renders
setCartCount(prev => prev + 1);
}, []); // Empty dependency array means it's created only once
return (
<div>
<h3>Product List</h3>
<p>Items in cart: {cartCount}</p>
{/* This button just forces the parent to re-render */}
<button onClick={() => setCartCount(c => c + 1)}>Re-render Parent</button>
{products.map(productName => (
// 2. ProductCard is memoized and receives a stable onAddToCart prop
<ProductCard
key={productName}
productName={productName}
onAddToCart={handleAddToCart}
/>
))}
</div>
);
}
When you click "Re-render Parent", ProductList re-renders, but the ProductCard components do not. Their productName prop is stable, and onAddToCart is stable thanks to useCallback. React.memo sees that the props are shallowly equal and skips re-rendering the children.
Fix expensive calculations with useMemo
While useCallback memoizes functions, useMemo memoizes a value. Use it to avoid re-computing expensive, derived data on every render.
Imagine filtering a list of 10,000 products. You don't want to run that filter every time a completely unrelated state variable changes.
const visibleProducts = useMemo(() => {
console.log('Filtering products...');
return allProducts.filter(p => p.category === filterCategory);
}, [allProducts, filterCategory]); // Only re-runs if these change
This hook runs the filter function and caches its result. On the next render, if allProducts and filterCategory are the same, useMemo returns the cached array without running the function again.
An important detail: useCallback(fn, deps) is just a shorthand for useMemo(() => fn, deps). They do the same thing, but useCallback is for functions and useMemo is for any other value.
Nail the dependency array
The dependency array is where memoization bugs happen. If you get it wrong, you'll either have stale data or no optimization at all.
The trap: An empty [] dependency array on a function that needs outside scope. This creates a stale closure. The function is created once and forever closes over the initial values of its scope.
function Counter() {
const [count, setCount] = useState(0);
// BUG: This callback has a stale closure over `count`
const logCount = useCallback(() => {
// `count` will always be 0 here, because the function
// was created on the first render and never updated.
console.log(`The count is: ${count}`);
}, []); // Empty array is the problem
return <button onClick={logCount}>Log Count</button>;
}
The eslint-plugin-react-hooks package is essential for catching missing dependencies. But you still need to understand the fix. Either add the dependency ([count]) or use a functional state update, which doesn't require the dependency: setCount(c => c + 1).
Also, useState setters (like setCount) are guaranteed by React to be stable. You never need to add them to a dependency array or wrap them in useCallback.
How to talk about memoization in an interview
You will be asked to optimize a slow component. Don't just list the hooks. Show your process.
Interviewer: "You have a page with a data grid that's slow to update when the user types in a search box. How would you investigate and fix this?"
Your thought process:
Diagnose first. "My first step would be to use the React DevTools Profiler to see what's actually slow. I need to know if the component is re-rendering too often, or if the render itself is expensive. I'd check the 'Ranked' chart to find the most expensive components."
Address unnecessary re-renders. "If the profiler shows that grid rows are re-rendering even when their data hasn't changed, I'd wrap the row component in
React.memo. Then, I'd check the props being passed to it. Any callback functions, likeonRowClick, need to be wrapped inuseCallbackin the parent. Any objects or arrays, like astyleprop, should be memoized withuseMemo."Address expensive calculations. "If the slowness is from the filtering logic itself running on every keystroke, I'd wrap that calculation in
useMemo. The dependencies would be the full list of items and the current search term. This ensures the filter only re-runs when it absolutely has to."State the trade-off. "Memoization isn't free; it uses memory and adds a comparison cost. I'd only apply these optimizations where the profiler demonstrates a clear performance gain that justifies the added complexity."
This answer shows you have a systematic, evidence-based approach to performance, which is what separates senior developers from junior ones.
Try it
Create a component that renders a list of 1,000 items. Add a text input that filters the list and a separate button that just increments a counter. Use the profiler to see the list re-render when the counter changes. Then, apply React.memo, useMemo, and useCallback to prevent the list from re-rendering unnecessarily.
Next: We'll cover how to contain crashes in your application with Error Boundaries for Robust UIs.
Lock it in — apply this lesson under interview conditions.