Skip to content

useLimitCallback

Limit invocations of a callback to at max period count.

The useLimitCallback hook is helpful when you want to limit the invocation of a calback to at max period count.

It can be used to create common utilities like limitOnce, limitTwice etc.

useLimitCallback

Count : 0

The increment function is limited to only 2 times if no reset is done.

Usage

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

./src/App.tsx
import React from 'react';
import { useLimitCallback } from '@abhushanaj/react-hooks';
function App() {
const [count, { increment }] = useCounter(0);
const [sampleByTwo, { reset }] = useLimitCallback(() => {
increment();
}, 2);
return (
<div>
<p>Count Value: {count}</p>
<button onClick={sampleByTwo}>Increment by 1</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default App;

Properties

  1. Negative period values passed are converted to positive values using Math.abs() utility.

API Reference

Parameters

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

Return Value

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

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

Types Reference

1. LimitControls

ParameterTypeDescriptionDefault
reset()=>voidResets the limit period back to zero. After calling the reset function, the callback can be invoked again for at max period times.N/A