useSampleCallback
Limits the invocation of a callback to every period samples.
The useSampleCallback
hook is helpful when you want to limit the invocation of a function to every period samples.
useSampleCallback
Count : 0
Increment is now sampled by a period of 2.Usage
Import the hook from @abhushanaj/react-hooks
and use in required component.
import React from 'react';import { useSampleCallback } from '@abhushanaj/react-hooks';
function App() { const [count, { increment }] = useCounter(0);
const [sampleByTwo, { reset }] = useSampleCallback(() => { increment(); }, 2);
return ( <div> <p>Count Value: {count}</p> <button onClick={sampleByTwo}>Increment by 1</button> <button onClick={reset}>Reset sampling</button> </div> );}
export default App;
API Reference
Parameters
Parameter | Type | Description | Default |
---|---|---|---|
callback | ()=>void | The function which needs to be sampled. | N/A |
period | ()=>void | The sampling period of the function. | N/A |
Return Value
The return value follow the structure of [fn, samplingControls]
.
Parameter | Type | Description | Default |
---|---|---|---|
fn | ()=>void | New sampled function over period. | N/A |
samplingControls | SamplingControls | Controls for the sampled callback. | N/A |
Types Reference
1. SamplingControls
Parameter | Type | Description | Default |
---|---|---|---|
reset | ()=>void | Resets the sampling period. After calling the reset function, the callback can be invoked again for every period samples. | N/A |