Performance & Optimization
useThrottle
Throttles a callback so it executes at most once per specified time interval.
About
Throttle custom hook for React
Examples
Basic usage
import React, { useState } from "react";
import { useThrottle } from "rooks";
function App() {
const [text, setText] = useState("");
const [throttleValue, setThrottleValue] = useState("");
const [throttledFunction, isReady] = useThrottle(setThrottleValue, 1000);
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>
);
}
export default App;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 |
Robustness and lifecycle
The throttle gate closes synchronously before invoking the callback, so repeated calls in the same event or React batch still execute at most once. The returned function remains stable and invokes the latest callback.