useMemo in React :👈 👉:useRef vs useState

useCallback Explained with Practical Examples

useCallback Explained with Practical Examples in React

1. Quick Answer

useCallback is a React Hook that caches a function definition between renders. React returns the cached function while its dependencies remain unchanged.

Use useCallback when:

  • You pass a function to a child component wrapped in React.memo and want to avoid unnecessary child renders.
  • A function is used as a dependency of another Hook, such as useEffect, and a stable function reference helps avoid unnecessary effect executions.
  • You have identified a performance problem that can be improved by preserving a function reference.

Rule of thumb: Do not wrap every function in useCallback. Use it when stable function identity provides a practical benefit.

2. Table of Contents

  1. Understanding Function References
  2. useCallback Syntax
  3. Example 1: Basic useCallback
  4. Example 2: Preventing Unnecessary Child Renders
  5. Example 3: Using useCallback with useEffect
  6. Example 4: Updating State Without Stale Values
  7. Example 5: Handling Lists of Items
  8. useCallback vs useMemo vs React.memo
  9. Understanding Dependencies
  10. Common Mistakes
  11. Performance Considerations
  12. Best Practices
  13. Interview Questions
  14. Summary

3. Understanding Function References

In JavaScript, functions are objects. When a function is created, it has a reference that can be compared with other function references.

Consider this React component:

import { useState } from "react";
function Counter() {
    const [count, setCount] = useState(0);
    function handleClick() {
        console.log("Button clicked");
    }
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={handleClick}>
                Click
            </button>
            <button onClick={() => setCount(count + 1)}>
                Increment Count
            </button>
        </div>
    );
}
export default Counter;

Whenever count changes, React renders Counter again. The component creates a new handleClick function during that render.

The new function may perform exactly the same work as the previous function, but it has a different reference.

Function Reference Example

const firstFunction = () => console.log("Hello");
const secondFunction = () => console.log("Hello");
console.log(firstFunction === secondFunction); // false

Although the functions contain the same code, they are two different function objects.

How useCallback Helps

const handleClick = useCallback(() => {
    console.log("Button clicked");
}, []);

React can return the same cached function reference across renders while its dependencies remain unchanged.

Conceptual Flow

Component Renders useCallback Checks Dependencies Dependencies Unchanged Dependencies Changed Reuse Cached Function Create and Cache a New Function Return Function

Important: React may discard cached functions in certain situations. Treat useCallback as a performance optimization, not as a guarantee that a function reference will persist forever.

4. useCallback Syntax

Syntax

const memoizedFunction = useCallback(
    () => {
        // Function logic
    },
    [dependency1, dependency2]
);
  • Function: The function definition that React can cache.
  • Dependencies: Reactive values used by the function that determine when a new function is needed.
  • Returned function: The cached function reference when dependencies remain unchanged, or a new function when they change.

Unlike useMemo, which caches the result of a calculation, useCallback caches a function reference.

5. Example 1: Basic useCallback

Suppose you have a counter and a function that logs a message.

import { useCallback, useState } from "react";
function Counter() {
    const [count, setCount] = useState(0);
    const handleMessage = useCallback(() => {
        console.log("The button was clicked");
    }, []);
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={handleMessage}>
                Log Message
            </button>
            <button onClick={() => setCount(count + 1)}>
                Increment Count
            </button>
        </div>
    );
}
export default Counter;

Here, handleMessage has no reactive dependencies. React can reuse its cached reference when the component renders again.

However, this example does not necessarily need useCallback. The function is inexpensive, and there is no memoized child or effect that benefits from its stable reference.

This example demonstrates the syntax, not a guaranteed performance improvement.

6. Example 2: Preventing Unnecessary Child Renders

One of the most common practical uses of useCallback is passing a function to a child component wrapped in React.memo.

Problem Without useCallback

import { memo, useState } from "react";
const Child = memo(function Child({ onClick }) {
    console.log("Child rendered");
    return (
        <button onClick={onClick}>
            Click Child
        </button>
    );
});
function Parent() {
    const [count, setCount] = useState(0);
    function handleClick() {
        console.log("Child button clicked");
    }
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>
                Increment Parent Count
            </button>
            <Child onClick={handleClick} />
        </div>
    );
}
export default Parent;

Why Does the Child Render Again?

  1. The parent component renders when count changes.
  2. The parent creates a new handleClick function.
  3. The child receives a different function reference.
  4. React.memo detects that the onClick prop changed.
  5. The child renders again.

Although Child is wrapped in React.memo, the changing function reference prevents the memoization from skipping the render.

Solution With useCallback

import { memo, useCallback, useState } from "react";
const Child = memo(function Child({ onClick }) {
    console.log("Child rendered");
    return (
        <button onClick={onClick}>
            Click Child
        </button>
    );
});
function Parent() {
    const [count, setCount] = useState(0);
    const handleClick = useCallback(() => {
        console.log("Child button clicked");
    }, []);
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>
                Increment Parent Count
            </button>
            <Child onClick={handleClick} />
        </div>
    );
}
export default Parent;

Now the callback reference remains stable while its dependencies are unchanged. If the child's other props also remain unchanged and its own state or context does not require an update, React can skip rendering the memoized child.

When Is This Useful?

  • The child performs expensive rendering work.
  • The child is wrapped in React.memo.
  • The callback reference is the reason the child receives a changed prop.
  • Profiling or the component structure indicates that avoiding the render is worthwhile.

For a small child component, allowing it to render again may be simpler and fast enough.

7. Example 3: Using useCallback with useEffect

Functions can also be dependencies of effects. If a function is recreated on every render, an effect that depends on it may run again on every render.

Problem

import { useEffect, useState } from "react";
function UserProfile({ userId }) {
    const [user, setUser] = useState(null);
    function loadUser() {
        console.log("Loading user:", userId);
    }
    useEffect(() => {
        loadUser();
    }, [loadUser]);
    return <p>{user ? user.name : "Loading user..."}</p>;
}

The loadUser function is recreated on every render. Since the function reference changes, the effect can run after every render. The example also does not actually load user data.

Solution 1: Define the Function Inside the Effect

If the function is only needed by the effect, defining it inside the effect is often the simplest approach.

import { useEffect, useState } from "react";
function UserProfile({ userId }) {
    const [user, setUser] = useState(null);
    useEffect(() => {
        function loadUser() {
            console.log("Loading user:", userId);
        }
        loadUser();
    }, [userId]);
    return <p>{user ? user.name : "Loading user..."}</p>;
}

The effect now depends directly on userId, which is the reactive value it needs.

Solution 2: Use useCallback

import { useCallback, useEffect, useState } from "react";
function UserProfile({ userId }) {
    const [user, setUser] = useState(null);
    const loadUser = useCallback(() => {
        console.log("Loading user:", userId);
    }, [userId]);
    useEffect(() => {
        loadUser();
    }, [loadUser]);
    return <p>{user ? user.name : "Loading user..."}</p>;
}

In this version, loadUser remains stable while userId is unchanged. The effect runs initially and when the callback changes because userId changes.

Recommendation: Prefer defining a function inside the effect when it is only needed there. Use useCallback when the function also needs to be shared with other parts of the component or passed to children.

8. Example 4: Updating State Without Stale Values

A callback can capture values from the render in which it was created. This is called a closure. If dependencies are missing, a memoized callback may continue using an outdated value.

Incorrect Example

import { useCallback, useState } from "react";
function Counter() {
    const [count, setCount] = useState(0);
    const increment = useCallback(() => {
        setCount(count + 1);
    }, []);
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={increment}>
                Increment
            </button>
        </div>
    );
}

The callback captures the initial value of count. Since the dependency array is empty, the callback continues using that old value and may repeatedly set the count to 1.

Solution 1: Include the Dependency

const increment = useCallback(() => {
    setCount(count + 1);
}, [count]);

This creates a new callback whenever count changes. It works correctly, but the function reference is no longer stable across count updates.

Solution 2: Use a Functional State Update

const increment = useCallback(() => {
    setCount(currentCount => currentCount + 1);
}, []);

This approach uses the previous state supplied by React, so the callback does not need to capture count. Its dependency array can remain empty.

Best practice: Include every reactive value used by a callback in its dependencies. When updating state based on its previous value, consider a functional state update to avoid capturing that state value unnecessarily.

9. Example 5: Handling Lists of Items

Suppose an application displays many products, and each product has an Add to Cart button. A callback can handle the action for a particular product.

Example

import { memo, useCallback, useState } from "react";
const ProductItem = memo(function ProductItem({ product, onAdd }) {
    console.log("Rendering:", product.name);
    return (
        <li>
            {product.name} - ₹{product.price}
            <button onClick={() => onAdd(product.id)}>
                Add to Cart
            </button>
        </li>
    );
});
function ProductList({ products }) {
    const [cart, setCart] = useState([]);
    const handleAdd = useCallback((productId) => {
        setCart(currentCart => [...currentCart, productId]);
    }, []);
    return (
        <div>
            <h2>Products</h2>
            <ul>
                {products.map(product => (
                    <ProductItem
                        key={product.id}
                        product={product}
                        onAdd={handleAdd}
                    />
                ))}
            </ul>
            <p>Items in cart: {cart.length}</p>
        </div>
    );
}
export default ProductList;

Why Does This Help?

  • The parent can render again when the cart changes.
  • The handleAdd function reference remains stable.
  • Product objects that retain their references can be passed unchanged.
  • React.memo can skip rendering product items whose props have not changed.

This optimization works best when the products array and individual product objects retain their references between parent renders. If the parent recreates every product object on each render, the children may still render again.

10. useCallback vs useMemo vs React.memo

Feature useCallback useMemo React.memo
Type React Hook React Hook Component memoization function
Purpose Cache a function reference. Cache a calculated value. Skip rendering a component when its props are unchanged.
Returns A function. A value. A memoized component.
Example Callback passed to a memoized child. Filtered or sorted data. Expensive child component.

useCallback Example

const handleClick = useCallback(() => {
    console.log("Clicked");
}, []);

useMemo Example

const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

React.memo Example

const Child = memo(function Child({ name }) {
    return <p>{name}</p>;
});

Easy way to remember:

  • useCallback caches a function.
  • useMemo caches the result of a calculation.
  • React.memo can skip rendering a component when its props are unchanged.

11. Understanding Dependencies

The dependency array tells React which reactive values determine whether a cached callback can be reused.

No Dependencies Array

const handleClick = useCallback(() => {
    console.log("Clicked");
});

This is invalid because useCallback requires a dependency array. Supply the array even if it is empty.

Empty Dependency Array

const handleClick = useCallback(() => {
    console.log("Clicked");
}, []);

The callback does not capture reactive values from the component, so its dependency array is empty.

Dependencies With Values

const showUser = useCallback(() => {
    console.log(userId);
}, [userId]);

Whenever userId changes, React creates and caches a new callback for the new value.

Important Dependency Rules

  • Include every reactive value used by the callback, including relevant props, state values, and functions declared in the component.
  • Do not omit dependencies merely to keep a function reference stable.
  • Use the React Hooks lint rules to help identify missing dependencies.
  • Functional state updates can sometimes remove the need to capture the current state value.
  • Do not use an empty dependency array when the callback depends on changing values.

12. Common Mistakes

Mistake 1: Using useCallback for Every Function

Memoization adds complexity. If a function is inexpensive and its reference is not used for a meaningful optimization, defining it normally is usually fine.

Mistake 2: Forgetting Dependencies

const updateUser = useCallback(() => {
    saveUser(userId);
}, []);

If userId changes, the callback may still use the previous value.

Correct:

const updateUser = useCallback(() => {
    saveUser(userId);
}, [userId, saveUser]);

This assumes saveUser is a reactive function defined outside the component or otherwise provided to it. If it is a function declared inside the component, its own reference may change on every render. Consider moving the logic inside the relevant effect, moving the function outside the component when appropriate, or stabilizing it at its source.

Mistake 3: Expecting useCallback to Prevent the Parent from Rendering

useCallback does not prevent a component from rendering when its state or props change. It only helps preserve a callback reference.

Mistake 4: Assuming React.memo Always Prevents Child Renders

A memoized child may still render when its own state or consumed context changes, when a prop changes, or when React determines that rendering is needed.

Mistake 5: Using useCallback to Fix Incorrect State Logic

Memoizing a function does not automatically make its state updates correct. Ensure dependencies are complete and use functional state updates when appropriate.

Mistake 6: Using useCallback for Side Effects During Rendering

useCallback defines a function; it does not execute that function by itself. Call event handlers in response to events and perform synchronization with external systems in an appropriate effect.

13. Performance Considerations

  • Measure before optimizing: Use React DevTools Profiler to identify unnecessary child renders.
  • Optimize expensive children: Stable callbacks are most useful when they help memoized children skip costly rendering.
  • Keep dependencies accurate: An incomplete dependency list can introduce bugs; changing dependencies can also create new callback references.
  • Consider the whole prop structure: A stable callback will not prevent a child render if other props change.
  • Avoid unnecessary memoization: Simple components may be fast enough without it.
  • Remember Strict Mode: Development behavior may include additional renders to help expose problems.

In newer React environments, the React Compiler can automatically memoize many values and functions when enabled and supported by the project. In such applications, manual use of useCallback may be less necessary. Follow the project's configuration and measure before adding manual memoization.

14. Best Practices

  • Use useCallback when preserving a function reference solves a specific problem.
  • Combine it with React.memo when stable callback props can help avoid expensive child renders.
  • Include all required reactive values in the dependency array.
  • Use functional state updates when the next state depends on the previous state.
  • Prefer defining effect-specific functions inside the effect when that simplifies dependencies.
  • Avoid using memoization as a substitute for correct state management.
  • Keep component props stable where practical, not just callbacks.
  • Use profiling to confirm that memoization improves performance.

15. Interview Questions

Q1. What is useCallback in React?

Answer: useCallback is a Hook that caches a function reference between renders while its dependencies remain unchanged.

Q2. Why is useCallback useful with React.memo?

Answer: It can preserve callback references passed as props, allowing a memoized child to skip rendering when its other props also remain unchanged.

Q3. What is the difference between useCallback and useMemo?

Answer: useCallback caches a function reference, while useMemo caches the result of a calculation.

Q4. Does useCallback prevent component re-rendering?

Answer: No. It preserves a function reference. It may help prevent unnecessary renders of memoized child components when their props remain unchanged.

Q5. What happens if a dependency changes?

Answer: React creates and caches a new callback using the current values of the dependencies.

Q6. Can useCallback cause stale closures?

Answer: Yes, if required dependencies are omitted. The callback may continue using values captured by an earlier render.

Q7. Should every event handler use useCallback?

Answer: No. Use it when a stable reference provides a practical performance or dependency-management benefit.

Q8. Can useCallback be used with useEffect?

Answer: Yes. It can stabilize a function used as an effect dependency. However, if the function is only needed inside the effect, defining it inside the effect is often simpler.

16. Summary

Situation Should You Use useCallback?
Passing a callback to an expensive memoized child Often useful
Simple event handler in a small component Usually unnecessary
Function used as an effect dependency Sometimes useful; consider defining it inside the effect
Updating state from its previous value Can be useful with a functional state update
Preventing a parent component from rendering No
Fixing missing dependencies or incorrect logic No; fix the underlying problem

Final recommendation: Think of useCallback as a way to preserve a function reference, not as a way to make every function faster. Use it when stable identity helps memoized children or effect dependencies, and keep your code simple when no meaningful benefit exists.

🔙
useMemo in React :👈 👉:useRef vs useState

Comments and Discussion