useCallback returns a memoized version of the callback that only changes if one of the dependencies has changed. This is useful for passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
Signature
Parameters
T extends Function
required
The callback function to memoize. This function will be returned on subsequent renders if the dependencies haven’t changed.
ReadonlyArray<unknown>
required
An array of dependencies. The callback will only be recreated if one of these values changes (compared using
===).Returns
Returns the memoized callback function of typeT. On the initial render, it returns the passed callback. On subsequent renders, it returns the same callback reference if dependencies haven’t changed, or a new callback if they have.
Basic Usage
With Dependencies
Passing to Child Components
Event Handlers
With useEffect
Debounced Callbacks
Callback Factories
With Context
Relationship with useMemo
useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). It’s a convenience hook specifically for memoizing functions.Use
useCallback when passing callbacks to optimized child components (wrapped in memo) that rely on reference equality to prevent unnecessary renders.Don’t use
useCallback everywhere. Only use it when:- Passing callbacks to memoized child components
- Using the callback as a dependency in other hooks like
useEffect - The callback is expensive to create