A React hook for always referencing the latest callback.
npm install @kopexa/use-callback-refA React hook for always referencing the latest callback.
---
@kopexa/use-callback-ref is a utility hook for React that ensures your callback always points to the latest function instance, even across re-renders. This is especially useful for event handlers, effects, and subscriptions where you want to avoid stale closures.
- Author: Kopexa (
- License: MIT
- Repository: kopexa-grc/sight
- Guarantees the latest callback reference
- Prevents unnecessary re-renders
- TypeScript support
- Lightweight and dependency-free (except React)
``sh`
pnpm add @kopexa/use-callback-refor
yarn add @kopexa/use-callback-refor
npm install @kopexa/use-callback-ref
`tsx
import { useCallbackRef } from '@kopexa/use-callback-ref';
function MyComponent() {
const handleClick = useCallbackRef(() => {
// Always the latest logic here
});
React.useEffect(() => {
window.addEventListener('click', handleClick);
return () => window.removeEventListener('click', handleClick);
}, [handleClick]);
return ;
}
`
- callback: The function you want to always reference the latest version of.
- Returns: A stable function reference that always calls the latest callback.
#### Example
`tsx``
const stableCallback = useCallbackRef((event) => {
// ...
});
- Use for event handlers, effects, and subscriptions.
- Avoid using for values that do not change or do not need to be stable.
Kopexa (
MIT © Kopexa