What You'll Learn
You'll learn how to use useCallback to create a stable function reference that won't cause your effects to re-run unnecessarily on every render.
The Problem Recap
When you define a function inside your component and include it in an effect's dependency array, React sees it as a new function on every render (even if the logic is identical). This causes your effect to run repeatedly.
The useCallback Solution
useCallback is a React Hook that memoizes (remembers) your function. It returns the same function reference across renders unless its own dependencies change:
import { useEffect, useCallback, useState } from 'react';
function SearchComponent({ apiKey }) {
const [query, setQuery] = useState('');
// Wrap the function with useCallback
const fetchResults = useCallback(() => {
console.log('Fetching:', query);
// API call logic here
}, [query]); // Only recreate if query changes
useEffect(() => {
fetchResults();
}, [fetchResults]); // Now safe to include!
return <input value={query} onChange={e => setQuery(e.target.value)} />;
}
How It Works
useCallback takes two arguments:
- The function you want to stabilize
- A dependency array (just like
useEffect)
The function only gets recreated when something in useCallback's dependency array changes. Otherwise, React returns the exact same function reference from the previous render.
The Analogy
Think of useCallback like a contract: "Keep using this same employee (function) unless their job requirements (dependencies) change."
Key Takeaway: Use useCallback to wrap functions that appear in effect dependency arrays, preventing unnecessary re-runs while keeping ESLint's exhaustive-deps rule satisfied.