Performance: useMemo hook
This affects the rendering speed and responsiveness by avoiding unnecessary recalculations during component renders.
import { useMemo } from 'react'; function Component({items}) { const total = useMemo(() => items.reduce((sum, item) => sum + item.value, 0), [items]); return <div>Total: {total}</div>; }
function Component({items}) { const total = items.reduce((sum, item) => sum + item.value, 0); return <div>Total: {total}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Without useMemo | No change | Multiple reflows if calculation triggers state changes | Higher paint cost due to slower JS | [X] Bad |
| With useMemo | No change | Single reflow if dependencies change | Lower paint cost due to cached results | [OK] Good |
useMemo hook in React?useMemo doesuseMemo stores a value and recalculates it only when its dependencies change, avoiding repeated work.useEffect or useState, not useMemo.useMemo in a React functional component?useMemo takes a function returning the value and an array of dependencies: useMemo(() => value, [deps]).const [count, setCount] = useState(0);
const double = useMemo(() => count * 2, [count]);
return <div>{double}</div>;count is 3?double value is computed as count * 2, and recalculated only when count changes.count is 3, double becomes 3 * 2 = 6.useMemo:const memoizedValue = useMemo(() => expensiveCalc(), []); // Later in code const result = memoizedValue();
useMemo returns the memoized value, not a function, so calling it as a function causes an error.memoizedValue(), but memoizedValue is the result of expensiveCalc(), not a function.useMemo best improves performance by avoiding unnecessary recalculations?users and searchTerm, so both must be in the dependency array.users or searchTerm change. const filteredUsers = useMemo(() => users.filter(u => u.name.includes(searchTerm)), []); never recalculates after first render. const filteredUsers = useMemo(() => users.filter(u => u.name.includes(searchTerm))); misses dependencies array. const filteredUsers = users.filter(u => u.name.includes(searchTerm)); recalculates every render.Pass the test and this pattern moves unknown