What is useMemo and when is it necessary?

useMemo is a performance optimization hook that allows you to "memoize" (cache) the result of an expensive calculation between renders.

How it works:

You pass a "create" function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed. If the dependencies are identical to the last render, it skips the calculation and returns the cached result.

When to use it:

  1. Expensive Math/Processing: If you are filtering a list of 10,000 items, parsing a massive string, or running a complex algorithm, you don't want to repeat that work on every single render.
  2. Referential Equality: If you need to pass an object or array down to an optimized child component (React.memo), wrapping the object creation in useMemo ensures the reference remains the same, preventing unnecessary child renders.

Warning: Don't use useMemo for trivial calculations (like a + b). The overhead of the hook itself is higher than the math.

Code example

tsx
1import React, { useState, useMemo } from 'react';
2
3export default function ProductFilter({ products }) {
4 const [filterText, setFilterText] = useState('');
5 const [isDarkTheme, setIsDarkTheme] = useState(false);
6
7 // 🚨 EXPENSIVE OPERATION
8 // Without useMemo, typing in the input OR toggling the theme
9 // would cause this entire array to be re-filtered.
10 // With useMemo, changing the theme skips this heavy calculation entirely.
11 const filteredProducts = useMemo(() => {
12 console.log("Running expensive filter operation...");
13
14 // Artificial delay to simulate heavy processing
15 const start = performance.now();
16 while (performance.now() - start < 100) {
17 // blocking loop
18 }
19
20 return products.filter(product =>
21 product.name.toLowerCase().includes(filterText.toLowerCase())
22 );
23 }, [products, filterText]); // Only re-run if products list or filter string changes
24
25 return (
26 <div className={isDarkTheme ? 'bg-gray-900 text-white p-6' : 'bg-white text-black p-6'}>
27 <div className="flex gap-4 mb-6">
28 <input
29 type="text"
30 value={filterText}
31 onChange={(e) => setFilterText(e.target.value)}
32 placeholder="Search products..."
33 className="border p-2 rounded text-black"
34 />
35 <button
36 onClick={() => setIsDarkTheme(!isDarkTheme)}
37 className="bg-purple-600 text-white px-4 py-2 rounded"
38 >
39 Toggle Theme (Instant)
40 </button>
41 </div>
42
43 <ul className="space-y-2">
44 {filteredProducts.map(p => (
45 <li key={p.id} className="p-3 border rounded">{p.name} - ${p.price}</li>
46 ))}
47 </ul>
48 </div>
49 );
50}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.

Open in study app