useMemo for Performance
In React, when a component re-renders, all the code inside it runs again, including expensive calculations. If these calculations don't need to run on every render (because their inputs haven't changed), you're wasting performance. **useMemo** helps by memoizing the result of these calculations.
What is useMemo?
useMemo is a React Hook that memoizes (caches) the result of a calculation. It only recalculates when one of its dependencies changes. Otherwise, it returns the cached value. This is useful for expensive computations like filtering large lists, complex mathematical operations, or data transformations.
Think of useMemo as a way to "remember" a computed value. If the inputs haven't changed, just give me the last result don't do the work again.
Syntax
const memoizedValue = useMemo(() => { <!-- expensive calculation --> return computeExpensiveValue(a, b);}, [a, b]); <!-- dependencies -->Example: Filtering a Large List
import React, { useState, useMemo } from 'react';
function ProductList({ products, category }) { <!-- Without useMemo: this runs on EVERY render --> const filteredProducts = products.filter( product => product.category === category );
<!-- With useMemo: only runs when products or category change --> const memoizedFilteredProducts = useMemo(() => { console.log('Filtering products...'); return products.filter(product => product.category === category); }, [products, category]);
return ( <ul> {memoizedFilteredProducts.map(product => ( <li key={product.id}>{product.name}</li> ))} </ul> );}Example: Expensive Calculation
function PrimeCalculator({ number }) { const isPrime = useMemo(() => { console.log('Checking if prime:', number); if (number <= 1) return false; for (let i = 2; i <= Math.sqrt(number); i++) { if (number % i === 0) return false; } return true; }, [number]);
return <p>{number} is {isPrime ? '' : 'not '}a prime number.</p>;}When to Use useMemo
- Expensive calculations (filtering, sorting, mathematical operations).
- Referential equality when passing objects/arrays as props to memoized children.
Two Minute Drill
- useMemo memoizes the result of expensive calculations.
- It only recalculates when dependencies change.
- Use it for filtering, sorting, or complex data transformations.
- Don't overuse simple calculations don't need memoization.
- The dependency array must include all values from the component scope that are used in the calculation.
Need more clarification?
Drop us an email at career@quipoinfotech.com
