stackademic

The leading education platform for anyone with an interest in software development.

useMemo

Memoize expensive calculations to skip work on unchanged dependencies

Overview

useMemo caches the result of a computation between renders. React recomputes only when dependencies change. Use it for expensive filtering, sorting, or object creation—not for every trivial calculation.

Syntax / Usage

import { useMemo, useState } from 'react'

function ProductList({ products, filter }) {
  const filtered = useMemo(() => {
    return products.filter((p) =>
      p.name.toLowerCase().includes(filter.toLowerCase())
    )
  }, [products, filter])

  const stats = useMemo(() => ({
    count: filtered.length,
    total: filtered.reduce((sum, p) => sum + p.price, 0),
  }), [filtered])

  return (
    <div>
      <p>{stats.count} items — ${stats.total}</p>
      <ul>{filtered.map((p) => <li key={p.id}>{p.name}</li>)}</ul>
    </div>
  )
}

Examples

Sort a large list only when data or sort key changes:

const sorted = useMemo(
  () => [...items].sort((a, b) => a.name.localeCompare(b.name)),
  [items]
)

Stabilize configuration passed to child components:

const chartOptions = useMemo(
  () => ({ responsive: true, plugins: { legend: { display: false } } }),
  []
)
return <Chart data={data} options={chartOptions} />

Common Mistakes

  • Memoizing cheap operations—the hook itself has overhead
  • Missing dependencies leading to stale memoized values
  • Using useMemo instead of useCallback for functions (use useCallback for function identity)
  • Over-memoizing everything, making code harder to read without measurable gain

See Also

use-callback use-state props components