useMemo Basics

Syntax

const result = useMemo(() => expensiveCalculation(a, b), [a, b]);

React runs the function on the first render and stores the result. On later renders it returns the stored result unless a or b changed.

Filtering a Big List

Example

Typing in the "note" box re-renders the component, but the slow filter only runs when the search text changes (watch the console).

import { useState, useMemo } from 'react';

const products = Array.from({ length: 5000 }, (_, i) => 'Product ' + (i + 1));

export default function App() {
  const [search, setSearch] = useState('');
  const [note, setNote] = useState('');

  const filtered = useMemo(() => {
    console.log('filtering for "' + search + '"');
    return products.filter((p) => p.includes(search));
  }, [search]);

  return (
    <div>
      <input placeholder="Search (e.g. 42)" value={search} onChange={(e) => setSearch(e.target.value)} />
      <input placeholder="Note (no filtering)" value={note} onChange={(e) => setNote(e.target.value)} />
      <p>{filtered.length} matches. First: {filtered.slice(0, 3).join(', ')}</p>
    </div>
  );
}

Result