Skip to content

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.

./src/App.tsx
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

ParameterTypeDescriptionDefault
callback()=>voidThe function which needs to be sampled.N/A
period()=>voidThe sampling period of the function.N/A

Return Value

The return value follow the structure of [fn, samplingControls].

ParameterTypeDescriptionDefault
fn()=>voidNew sampled function over period.N/A
samplingControlsSamplingControlsControls for the sampled callback.N/A

Types Reference

1. SamplingControls

ParameterTypeDescriptionDefault
reset()=>voidResets the sampling period. After calling the reset function, the callback can be invoked again for every period samples.N/A