useCallback()
Useful Resources:
What
A React hook that caches a function so it doesn’t get recreated on every render.
Similar to
useMemo, but instead of caching a value, it caches a function reference.
Why
Prevents unnecessary re-runs of
useEffector re-renders of child components caused by new function references in each render.Fixes referential equality problems (a new function is technically a new object, even if the logic is the same).
How (Basic Example)
👉 getItems is recreated only when number changes, not when unrelated state (like theme) changes.
How (With Parameters)
👉 Unlike useMemo, useCallback still gives you back a function you can call later with arguments.
When Not to Use
Don’t use it just for every function — creating small functions is cheap.
Use it mainly when:
Passing functions as props to memoized children.
Functions appear in a dependency array (
useEffect,useMemo).
Rare case: if creating the function itself is really slow (almost never happens).
useMemo vs useCallback
useMemo vs useCallbackuseMemo
Value (the result of a function)
Cache a calculated value so it doesn’t recompute every render
js const doubled = useMemo(() => slowDouble(num), [num]); → doubled is a number
useCallback
Function (the function itself)
Cache a function reference so it doesn’t get recreated every render
js const getItems = useCallback(() => [num, num+1], [num]); → getItems is a function
✅ Think of it like this:
useMemo→ “Give me the answer now, but cache it.”useCallback→ “Give me the formula (function) itself, but cache it.”
🧑💻 Tiny Real Example
👉 In short:
Use
useMemowhen you need to store a computed value.Use
useCallbackwhen you need to store a function.
Last updated