useThrottle
Aboutβ
Throttle custom hook for React
Installationβ
npm install --save rooks
Importing the hookβ
import { useThrottle } from "rooks";
Usageβ
function Demo() {
const [text, setText] = useState("");
const [throttleValue, setThrottleValue] = useState("");
const [throttledFunction, isReady] = useThrottle(setThrottleValue, 1000);
// isReady is a boolean that tells you whether calling throttledFn at that point
// will fire or not.
// Once the timeout of 1000ms finishes, isReady will become true to indicate that the next time
// throttledFn is called it will run right away.
return (
<div>
<h1>Rooks : useThrottle example</h1>
<input
onChange={(e) => {
setText(e.target.value);
throttledFunction(e.target.value);
}}
/>
<p>Actual value: {text}</p>
<p>
Throttled value (being updated at most once per second): {throttleValue}
</p>
</div>
);
}
render(<Demo />);
Argumentsβ
Argument | Type | Description | Default value |
---|---|---|---|
callback (required) | Function | Function that needs to be throttled | undefined |
timeout (optional) | Number | Time to throttle the callback in ms | 300 |
Return valueβ
Return value | Type | Description |
---|---|---|
throttledFunction | Function | A throttled function that will run at most once per timeout ms |
isReady | Boolean | Tells whether calling throttledFunction at that point will fire or not |
Codesandbox Exampleβ
Basic usageβ
Join Bhargav's discord serverβ
You can click on the floating discord icon at the bottom right of the screen and talk to us in our server.