How to Use useMemo for Performance in React
Use React's
useMemo hook to memoize expensive calculations so they only run when their dependencies change, improving performance by avoiding repeated work. Wrap the calculation in useMemo with a dependency array to control when it updates.Syntax
The useMemo hook takes two arguments: a function that returns a value, and an array of dependencies. It returns the memoized value, recalculating only when dependencies change.
useMemo(() => expensiveCalculation(), [deps])- Function: The calculation to memoize.
- Dependencies: Variables that trigger recalculation when changed.
javascript
const memoizedValue = useMemo(() => { // expensive calculation return computeSomething(); }, [dependency1, dependency2]);
Example
This example shows a component that calculates the factorial of a number. The factorial calculation is expensive, so useMemo caches the result and only recalculates when the number changes.
javascript
import React, { useState, useMemo } from 'react'; function factorial(n) { console.log('Calculating factorial'); return n <= 1 ? 1 : n * factorial(n - 1); } export default function FactorialCalculator() { const [number, setNumber] = useState(5); const [text, setText] = useState(''); const fact = useMemo(() => factorial(number), [number]); return ( <div> <input type="number" value={number} onChange={e => setNumber(Number(e.target.value))} aria-label="Number input" /> <p>Factorial: {fact}</p> <input type="text" value={text} onChange={e => setText(e.target.value)} placeholder="Type here" aria-label="Text input" /> <p>Typed text: {text}</p> </div> ); }
Output
When you change the number input, 'Calculating factorial' logs and factorial updates. Changing the text input does not recalculate factorial, improving performance.
Common Pitfalls
Common mistakes when using useMemo include:
- Not providing dependencies or providing incorrect dependencies, causing stale or unnecessary recalculations.
- Using
useMemofor cheap calculations, which adds unnecessary complexity. - Expecting
useMemoto prevent all re-renders; it only memoizes values, not components.
javascript
import React, { useState, useMemo } from 'react'; // Wrong: missing dependencies function WrongExample({ num }) { const value = useMemo(() => num * 2, []); // never updates when num changes return <p>{value}</p>; } // Right: correct dependencies function RightExample({ num }) { const value = useMemo(() => num * 2, [num]); return <p>{value}</p>; }
Quick Reference
- Use
useMemoto memoize expensive calculations. - Always specify correct dependencies.
- Do not use for cheap or simple calculations.
- It memoizes values, not components.
- Helps avoid unnecessary recalculations on re-renders.
Key Takeaways
Use
useMemo to cache expensive calculations and improve performance.Always provide the correct dependency array to control when recalculation happens.
Avoid using
useMemo for simple or cheap calculations to keep code clean.useMemo memoizes values, not component renders.Check console logs or React DevTools to verify memoization effects.