Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 16.4 — useMemo and useCallback
React · Example 2 of 2

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.

01

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.

02

A memoised <TodoItem onToggle={...} /> list re-renders every item when one is toggled. Make the callback stable.

Explain it without notes

01

What is the difference between useMemo and useCallback?

02

Give two situations where useMemo or useCallback really help.

03

Why is useCallback useless when the function is passed to a plain <button>?

04

What problems can a wrong dependency list cause?

useCallback makes memo work

Preview

Press Run to see the page.

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