1. Import both hooks
useMemo and useCallback are both imported from react.
import { useCallback, useMemo } from "react";Typorithm · medium
Step 1 of 8 · intro card
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.
useMemo caches a value, recomputed when deps change.
useCallback caches a function identity.
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]);Connect each part of the code to the concept before you type.
useMemo and useCallback are both imported from react.
import { useCallback, useMemo } from "react";useMemo caches the sorted array and recomputes only when items changes.
const sorted = useMemo(() => items.slice().sort(), [items]);The dependency array keys the cache; a new items reference triggers recomputation.
[items]useCallback returns a stable function identity that survives re-renders.
const onClick = useCallback(() => {The function identity changes only when id changes, so memoized children stay stable.
}, [id]);Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.