React HooksHard
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:
- 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.
- Referential Equality: If you need to pass an object or array down to an optimized child component (
React.memo), wrapping the object creation inuseMemoensures 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';23export default function ProductFilter({ products }) {4 const [filterText, setFilterText] = useState('');5 const [isDarkTheme, setIsDarkTheme] = useState(false);67 // 🚨 EXPENSIVE OPERATION8 // Without useMemo, typing in the input OR toggling the theme9 // 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...");1314 // Artificial delay to simulate heavy processing15 const start = performance.now();16 while (performance.now() - start < 100) {17 // blocking loop18 }1920 return products.filter(product =>21 product.name.toLowerCase().includes(filterText.toLowerCase())22 );23 }, [products, filterText]); // Only re-run if products list or filter string changes2425 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 <input29 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 <button36 onClick={() => setIsDarkTheme(!isDarkTheme)}37 className="bg-purple-600 text-white px-4 py-2 rounded"38 >39 Toggle Theme (Instant)40 </button>41 </div>4243 <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.