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.
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
Parameter | Type | Description | Default |
---|---|---|---|
callback | CallbackWithArgs<T> | The function call which needs to be fresh at all times. | N/A |
Return Value
Parameter | Type | Description | Default |
---|---|---|---|
fn | CallbackWithArgs<T> | Function with fresh args. | N/A |
Types Reference
CallbackWithArgs<T>
:(...args: Array<T>) => void