Typorithm · medium

useMemo & useCallback

react-usememoreactusememousecallbackmemoize
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn useMemo & useCallback

0%

Hooks

useMemo caches a computed value between renders, recomputing only when its deps change; useCallback caches a function identity so memoized children do not re-render. Both are dependency-array-keyed optimizations — don't overuse them, they have their own cost.

useMemo caches the result of a computation across renders. Here items.slice().sort() runs only when items changes; otherwise React hands back the cached sorted array instead of sorting again on every render.

useCallback caches a function's identity. Each render normally creates a fresh function, which would break memoized child components that compare props by reference. useCallback keeps the same onClick reference until id changes.

Both are keyed by the dependency array, just like useEffect, and both are optimizations — not correctness tools. They carry their own bookkeeping cost, so reach for them when a computation is expensive or a stable identity actually matters, not by default.

01

useMemo caches a value, recomputed when deps change.

02

useCallback caches a function identity.

03

Both are optimizations — don't overuse them.

import { useCallback, useMemo } from "react";

const sorted = useMemo(() => items.slice().sort(), [items]);

const onClick = useCallback(() => {
  doSomething(id);
}, [id]);

Read the implementation

Connect each part of the code to the concept before you type.

1. Import both hooks

useMemo and useCallback are both imported from react.

import { useCallback, useMemo } from "react";

2. Memoize a value

useMemo caches the sorted array and recomputes only when items changes.

const sorted = useMemo(() => items.slice().sort(), [items]);

3. Memo dependency

The dependency array keys the cache; a new items reference triggers recomputation.

[items]

4. Memoize a function

useCallback returns a stable function identity that survives re-renders.

const onClick = useCallback(() => {

5. Callback dependency

The function identity changes only when id changes, so memoized children stay stable.

}, [id]);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

useMemo & useCallback: Lesson & Practice · Typorithm | ApplyDjinn