Wrapping Functions with useCallback
What you'll learn: How to use useCallback to keep function references stable so they don't break your useEffect dependencies.
The Problem: Functions Change Every Render
Remember from the previous lesson that when you include a function in a dependency array, it creates problems because JavaScript creates a new function instance on every render—even if the code is identical. This causes your effect to re-run constantly.
The Solution: useCallback Memoizes Your Function
useCallback is a React Hook that "remembers" your function between renders. It only creates a new function instance when its own dependencies change.
Here's the pattern:
const handleSearch = useCallback(() => {
fetchResults(query);
}, [query]);
useEffect(() => {
handleSearch();
}, [handleSearch]); // ✅ Now safe!
Without useCallback, handleSearch would be a new function every render, triggering the effect every time. With useCallback, React only creates a new handleSearch when query changes.
Think of It Like This
Imagine a vending machine that dispenses function references. Without useCallback, you get a "new" candy bar (function) every time, even though it looks identical. With useCallback, the machine says, "Same ingredients as last time? Here's the same candy bar back."
When to Use It
Use useCallback when:
- A function needs to be in a dependency array
- A function is passed to child components that use
React.memo - You're hitting the "exhaustive-deps" ESLint warning for functions
Key Takeaway: useCallback stabilizes function references across renders, making functions safe to include in dependency arrays without causing unnecessary effect re-runs.