The useCallback Hook Signature
What you'll learn: How useCallback accepts a function and dependency array to control when that function gets recreated.
The Basic Structure
Just like useMemo memoizes values, useCallback memoizes functions. The hook takes two arguments:
const memoizedFunction = useCallback(
() => {
// your function logic here
},
[dependencies]
);
Understanding the Two Arguments
First Argument: The Function to Memoize
This is the actual function you want to preserve between re-renders. It can be any function—an event handler, a callback passed to a child component, or any function you want to keep stable.
Second Argument: The Dependency Array
This works exactly like useMemo's dependency array. React will only create a new function instance when one of these dependencies changes. If the dependencies haven't changed, React returns the same function reference from the previous render.
Why the Dependency Array Matters
Think of it like a security system: the dependency array tells React, "Only give me a new function if any of these values have changed." If you pass an empty array [], you get the same function for the component's entire lifetime. If you list variables the function uses, React creates a fresh function whenever those variables update.
const handleClick = useCallback(() => {
console.log(count); // uses 'count'
}, [count]); // recreate only when count changes
Key Takeaway: useCallback takes a function and a dependency array—it returns the same function reference until dependencies change, preventing unnecessary recreation across re-renders.