Course contentsShow
← React
Lesson 641 of 2,39617. Common useEffect MistakesFree lesson

Stable References with useCallback

Apply useCallback to functions passed as dependencies, ensuring callbacks don't change unless their inputs change.

Stable References with useCallback

What You'll Learn

You'll learn how useCallback prevents functions from changing identity on every render, solving dependency-related bugs and infinite loops in useEffect.

The Problem with Function Dependencies

Every time your component renders, any function you define inside it is recreated from scratch. Even if the function's logic is identical, React sees it as a different function because it has a new memory address.

When you list a function in useEffect's dependency array, React compares it by reference. A new reference means "the dependency changed," so the effect runs again. If that effect updates state, you render again, recreating the function... and you've got an infinite loop.

How useCallback Provides Stability

useCallback wraps your function and returns the same reference across renders—unless its own dependencies change. Think of it like a vault: the function inside stays locked and unchanged until you provide new inputs.

const handleClick = useCallback(() => {
  console.log(count);
}, [count]); // Only changes when count changes

Now when you include handleClick in an effect's dependency array, React won't see it as "changed" on every render—only when count actually changes.

When to Use It

Apply useCallback when:

  • A function is listed in useEffect's dependencies
  • The linter complains about a missing function dependency
  • You're passing callbacks to memoized child components

Without it, your effect runs unnecessarily or infinitely.

Example in Context

const fetchUser = useCallback(() => {
  fetch(`/api/user/${userId}`).then(/*...*/);
}, [userId]);

useEffect(() => {
  fetchUser();
}, [fetchUser]); // Stable reference prevents loops

Key Takeaway: useCallback ensures functions have stable references across renders, preventing infinite loops and unnecessary effect re-runs when those functions appear in dependency arrays.