Command Palette

Search for a command to run...

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

Counting calculations with and without useMemo

Five renders in total. The plain filter ran five times, the memoised one twice: once on mount and once when maxPrice changed. (Writing to outside counters during render breaks purity; it's done here only to count. In StrictMode the numbers would double.)

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?

Counting calculations with and without useMemo

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

After 3 dark-mode toggles: plain = 4 memo = 1
After 1 price change:      plain = 5 memo = 2