useMemo
Definition
`useMemo` is a React Hook that lets you cache the result of a calculation between re-renders. It prevents expensive operations from running on every single render.
Explain Like I'm New
Imagine you have to do really hard math (like calculating the square root of 10 million numbers). Doing it takes 5 seconds. If you do it once, you should write the answer on a sticky note (`useMemo`). The next time someone asks, instead of doing the math again, you just read the sticky note. You only throw away the note and recalculate if the numbers you were asked to calculate actually change.
Real World Example
If you have a massive array of 10,000 users and you want to filter them to only show 'Active' users, you wrap that filtering logic in `useMemo`. If the user types in an unrelated 'Dark Mode' toggle (causing a re-render), React won't needlessly re-filter the 10,000 users.
Common Use Cases
- •Preventing expensive, CPU-heavy calculations from running on every render
- •Keeping an object or array reference stable so it doesn't trigger unnecessary `useEffect` runs
Architecture & Flow
Interactive Example
import React, { useState, useMemo } from 'react'; export default function ExpensiveComponent() { const [count, setCount] = useState(0); const [text, setText] = useState(''); // useMemo: Only recalculates when 'count' changes. // Typing in the text input will NOT trigger this expensive loop! const expensiveResult = useMemo(() => { console.log("Running expensive calculation..."); let sum = 0; // Simulating a very heavy computation for (let i = 0; i < 100000000; i++) { sum += count; } return sum; }, [count]); return ( <div> <h2>Count: {count}</h2> <h2>Expensive Math Result: {expensiveResult}</h2> <button onClick={() => setCount(c => c + 1)}>Increment Count</button> <br /><br /> {/* Typing here causes re-renders, but useMemo protects the math! */} <input type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="Type here..." /> </div> ); }
Interview Questions
basic
- What is the primary purpose of `useMemo`?
- What two arguments does `useMemo` take?
intermediate
- Why shouldn't you wrap EVERY variable in your app with `useMemo`?
- What happens if you leave the dependency array empty `[]` in `useMemo`?
advanced
- Does `useMemo` prevent a component from re-rendering?
- Can React randomly throw away the `useMemo` cache?
trick
- Is it safe to run a side effect (like fetching data) inside `useMemo`?