React Hooks Series
useCallback
Cache a function definition so it keeps the same reference between renders. Essential when passing callbacks to optimised child components that rely on reference equality to skip re-renders.
01 — What it is
01
The signatureconst memoizedFn = useCallback(() => {
doSomething(a, b);
}, [a, b]); // recreate only when a or b changesuseCallback(fn, deps) is equivalent to useMemo(() => fn, deps) — it memoizes the function itself rather than its return value.02
Why it matters — referential equalityEvery render creates a new function instance. Without useCallback, a child wrapped in React.memo will still re-render because the function prop is technically a different object each time, even if the logic is identical.
// Without useCallback — new function every render
const handleClick = () => doSomething(data);
// With useCallback — same reference until 'data' changes
const handleClick = useCallback(
() => doSomething(data),
[data]
);02 — Live demo
↓
CallbackTutorial — interactiveToggle re-renders the parent but the Child keeps the same function reference — check your browser console to see that Child only logs when data actually changes.
Yo, please star the repo! — thanks!
Toggle re-renders parent but Child keeps the same function reference — check console for re-render logs
03 — useMemo vs useCallback
| Hook | Caches | Returns |
|---|---|---|
| useMemo | Result of a function call | A value |
| useCallback | The function itself | A function |
Next: useLayoutEffect — like useEffect but fires synchronously before the browser paints.