Callback Identity
Predict Output Medium
Question
What does this code print?
Code
function App() {
const [n, setN] = useState(0);
const cb1 = () => n;
const cb2 = useCallback(() => n, [n]);
// After setN(n) (same value), are cb1 and cb2 same as before?
}
Hint
useCallback returns same reference if deps unchanged.
Explanation
cb1 is a new function every render (different reference). cb2 is memoized with [n]; if n does not change (setN with same value), cb2 keeps the same reference. So cb1 identity changes, cb2 stays the same.
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.