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 useEffect or 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)

const getItems = useCallback(() => {
  return [number, number + 1, number + 2];
}, [number]);

<List getItems={getItems} />

👉 getItems is recreated only when number changes, not when unrelated state (like theme) changes.


  • How (With Parameters)

const getItems = useCallback((increment) => {
  return [number + increment, number + 1 + increment, number + 2 + increment];
}, [number]);

getItems(5); // returns [num+5, num+6, num+7]

👉 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:

      1. Passing functions as props to memoized children.

      2. Functions appear in a dependency array (useEffect, useMemo).

    • Rare case: if creating the function itself is really slow (almost never happens).


useMemo vs useCallback

Hook
What it returns
Use case
Example

useMemo

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

// ❌ Without memo/callback
const doubled = slowDouble(num);       // recalculates every render
const getItems = () => [num, num + 1]; // new function every render

// ✅ With useMemo
const doubled = useMemo(() => slowDouble(num), [num]); 
// only recalculates when num changes

// ✅ With useCallback
const getItems = useCallback(() => [num, num + 1], [num]);
// same function reference unless num changes

👉 In short:

  • Use useMemo when you need to store a computed value.

  • Use useCallback when you need to store a function.

Last updated