useThrottle is a custom React hook that limits how often a function can be called by ensuring it's invoked at most once within a specified delay period.
npm install @ehsaneha/react-throttlebash
npm install @ehsaneha/react-throttle
`
or
`bash
yarn add @ehsaneha/react-throttle
`
---
๐ง Usage
`tsx
import React, { useState } from "react";
import { useThrottle } from "@ehsaneha/react-throttle";
const ScrollLogger = () => {
const throttledLog = useThrottle((val: string) => {
console.log("Throttled value:", val);
}, 1000); // Run once every 1000ms
const handleScroll = (e: React.UIEvent) => {
throttledLog(e.currentTarget.scrollTop.toString());
};
return (
...
);
};
`
---
๐ง Hook Signature
`ts
function useThrottle void>(
callback: T,
delay: number
): T;
`
$3
- callback: The function you want to throttle.
- delay: The minimum time interval (in ms) between function calls.
$3
- A throttled version of your function.
---
โ
Features
- Type-safe and framework-agnostic
- Debounce alternative for scroll/input/resize
- Cleans up timers on unmount
- Compatible with React 18 and 19
---
๐งช Testing
Tested with @testing-library/react and jest`. Includes: