Loading

Quipoin Menu

Learn • Practice • Grow

react / useMemo Hook
tutorial

useMemo Hook

Imagine you have a component that performs an expensive calculation (like filtering a large list) every time it renders, even when the inputs haven't changed. That's wasteful. `useMemo` helps you optimize by memoizing (caching) the result of a calculation.

What is useMemo?

`useMemo` is a React Hook that memoizes the result of a function. It only recalculates the value when one of its dependencies changes. Otherwise, it returns the cached value.

Think of `useMemo` as a way to "remember" a computed value so you don't have to recompute it on every render unless necessary.

Syntax
const memoizedValue = useMemo(() => {
  <!-- expensive calculation -->
  return computeExpensiveValue(a, b);
}, [a, b]); <!-- dependencies -->

Example: Filtering a List
import React, { useState, useMemo } from 'react';

function ProductList({ products, filterText }) {
  const filteredProducts = useMemo(() => {
    console.log('Filtering products...');
    return products.filter(product =>
      product.name.toLowerCase().includes(filterText.toLowerCase())
    );
  }, [products, filterText]); <!-- Only re-run when products or filterText change -->

  return (
    <ul>
      {filteredProducts.map(product => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

Example: Expensive Calculation
function Fibonacci({ n }) {
  const fib = useMemo(() => {
    const calculateFib = (num) => {
      if (num <= 1) return num;
      return calculateFib(num - 1) + calculateFib(num - 2);
    };
    return calculateFib(n);
  }, [n]);

  return <p>Fibonacci({n}) = {fib}</p>;
}

When Not to Use useMemo

  • For simple calculations that aren't expensive.
  • If the dependencies change often, the overhead of memoization might outweigh the benefits.

Two Minute Drill

  • `useMemo` memoizes the result of a function and only recomputes when dependencies change.
  • Use it to optimize expensive calculations, filtering, or sorting that depend on specific values.
  • The dependency array tells React when to recalculate empty array means compute once.
  • Don't overuse it; only apply to genuinely expensive operations.
  • `useMemo` is for values, while `useCallback` is for functions.

Need more clarification?

Drop us an email at career@quipoinfotech.com