useCallbackRef is a custom hook that stores a callback in a ref, providing a stable function reference that always calls the latest callback. This is useful for preventing unnecessary re-renders or effect re-executions when callbacks are passed as props or dependencies.
Installation
Function Signature
Parameters
T | undefined
required
The callback function to be converted to a stable ref-based function. Can be
undefined.Return Value
T
A memoized function that always calls the latest version of the provided callback. The function reference remains stable across re-renders.
Usage
Basic Example
Preventing Re-renders
Event Handler with Latest Props
Type Definition
Implementation Details
The hook works by:- Storing the callback in a ref using
useRef - Updating the ref value on every render using
useEffect - Returning a memoized function that calls the current ref value
- The returned function reference never changes
- The callback always executes with the latest closure
- No unnecessary re-renders or effect re-executions
Notes
This hook is particularly useful when you need to pass callbacks to child components or effect dependencies while ensuring they don’t trigger unnecessary updates.
The implementation addresses React issue #19240 regarding callback refs and stale closures.