useCallback makes memo work
The script types two letters. The inline-handler button renders on every keystroke; the useCallback one is skipped. Both buttons still work: try clicking them.
useMemo(fn, deps) caches the result of a calculation and useCallback(fn, deps) caches a function, both until a dependency changes; they help when a calculation is slow or when a stable reference lets memo or an effect skip work, and they are noise everywhere else.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
A SearchResults component sorts 5,000 products by sortKey and also has an isMenuOpen state. Cache the sort so opening the menu doesn't sort again.
A memoised <TodoItem onToggle={...} /> list re-renders every item when one is toggled. Make the callback stable.
Explain it without notes
What is the difference between useMemo and useCallback?
Give two situations where useMemo or useCallback really help.
Why is useCallback useless when the function is passed to a plain <button>?
What problems can a wrong dependency list cause?
Preview
Console
Nothing logged yet.Expected console output
App rendered, text = ""
Inline handler rendered
useCallback handler rendered
App rendered, text = "h"
Inline handler rendered
App rendered, text = "hi"
Inline handler rendered