useMemo Cache
Predict Output Medium
Question
What does this code print?
Code
function App() {
const [n, setN] = useState(1);
const [c, setC] = useState(0);
const val = useMemo(() => n * 10, [n]);
// setC(c+1) — does val recompute?
return <p>{val}</p>;
}
Hint
useMemo only recomputes when n changes, not c.
Explanation
useMemo depends on [n]. Changing c triggers a re-render but val is not recomputed (cached). val stays 10 until n changes. This is the memoization benefit.
Related Resources
Related Lessons
- Memoization
Learn memoization.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.