Skip to main content
Version: 5.8.1

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​

ArgumentTypeDescriptionDefault value
callback (required)FunctionFunction that needs to be throttledundefined
timeout (optional)NumberTime to throttle the callback in ms300

Return value​

Return valueTypeDescription
throttledFunctionFunctionA throttled function that will run at most once per timeout ms
isReadyBooleanTells 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.