When to Use useMemo in React: Simple Guide and Examples
useMemo in React to remember the result of a costly calculation between renders and avoid repeating it unnecessarily. It helps improve performance by recalculating only when its dependencies change.How It Works
useMemo is like a memory box that keeps the result of a calculation safe until something it depends on changes. Imagine you bake a cake that takes a long time to prepare. Instead of baking it every time someone asks, you keep it ready and only bake a new one if the recipe changes.
In React, when a component re-renders, all its code runs again. If you have a heavy calculation, it can slow things down. useMemo tells React to remember the last result and reuse it unless the inputs (dependencies) change. This way, React skips the expensive work and speeds up rendering.
Example
This example shows how useMemo caches a slow calculation and only recalculates when the input number changes.
import React, { useState, useMemo } from 'react'; function SlowSquare({ number }) { const squared = useMemo(() => { console.log('Calculating square...'); // Simulate slow calculation let result = 0; for (let i = 0; i < 1e7; i++) { result += number * number; } return result; }, [number]); return <div>Square: {squared}</div>; } export default function App() { const [num, setNum] = useState(2); const [count, setCount] = useState(0); return ( <div> <SlowSquare number={num} /> <button onClick={() => setNum(num + 1)}>Increase Number</button> <button onClick={() => setCount(count + 1)}>Re-render</button> <p>Re-render count: {count}</p> </div> ); }
When to Use
Use useMemo when you have a calculation or operation that takes noticeable time or resources and you want to avoid doing it on every render. It is helpful when:
- You compute derived data from props or state that is expensive.
- You want to prevent unnecessary recalculations when unrelated parts of the component update.
- You pass memoized values to child components to avoid unnecessary re-renders.
For example, filtering a large list, complex math, or formatting data can benefit from useMemo. Avoid using it for cheap calculations as it adds complexity without benefit.
Key Points
- Memoizes a value between renders based on dependencies.
- Improves performance by skipping expensive recalculations.
- Only recalculates when dependencies change.
- Use wisely to avoid unnecessary complexity.
- Does not memoize functions—use
useCallbackfor that.