Skip to content

useFreshCallback

Returns the latest and fresh callback function.

The useFreshCallback hook is helpful when you want to get the latest and most fresh value of a function. It is useful when you don’t want stale values on callbacks.

This is derived from useFreshRef.

useFreshCallback

Count Value: 0

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
import React from 'react';
import { useFreshCallback } from '@abhushanaj/react-hooks';
function App() {
const [count, setCount] = React.useState(0);
const increment = () => {
setCount(count + 1);
};
const callback = useFreshCallback(increment);
React.useEffect(() => {
const timerId = setInterval(callback, 1000);
return () => {
clearInterval(timerId);
};
}, []);
return (
<div>
<p>Count Value: {count}</p>
</div>
);
}
export default App;

API Reference

Parameters

ParameterTypeDescriptionDefault
callbackCallbackWithArgs<T>The function call which needs to be fresh at all times.N/A

Return Value

ParameterTypeDescriptionDefault
fnCallbackWithArgs<T>Function with fresh args.N/A

Types Reference

  1. CallbackWithArgs<T> : (...args: Array<T>) => void