What is useMemo and why is it useful?
useMemo
is a Hook that memoizes the result of a function — it only recomputes the result when one of its dependencies changes. This optimization can avoid expensive calculations on every render.
Syntax:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
When to use useMemo
:
- Expensive calculations that don't need to run on every render.
- Keeping derived state that depends on props or state.
- Optimizing performance by preventing unnecessary recalculations.
⚡ Note: Don't overuse useMemo
for every little calculation. Use it mainly when you face real performance bottlenecks.