useThrottle
A custom React hook for throttling the updates of a value.
Play
Usage
import { useState } from "react";
import { useThrottle } from "@cannonui/reacthooks";
const TestUseThrottle = () => {
const [value, setValue] = useState(0);
const throttleValue = useThrottle(value, 2000);
const handleClick = () => {
setValue((prev) => prev + 1);
};
return (
<div>
<button onClick={handleClick}>invoke fn</button>
<div>value: {value}</div>
<div>throttle value: {throttleValue}</div>
</div>
);
};
export default TestUseThrottle;
Return Value
The hook returns the throttled value, which is updated based on the provided interval.
Parameters
Name | Type | Default | Description |
---|---|---|---|
value | any | The value to be throttled. | |
interval | number | 100 | The interval (in milliseconds) at which to update the throttled value. Defaults to 100ms (0.1 seconds). |
Features
- Throttles the updates of a value based on the specified interval.
- Returns the throttled value that is updated at the defined interval.
Example
In this example, we have a component called TestUseThrottle
that uses the useThrottle
hook to throttle the updates of a value. When the “Invoke function” button is clicked, the value
state is incremented by 1. However, the displayed throttleValue
will only update every 2 seconds (2000ms), preventing rapid updates and optimizing performance for certain scenarios.
Use Scenario
The useThrottle
hook is useful in scenarios where you want to limit the frequency of updates to a value, especially for computationally expensive operations or for handling rapid user interactions like input events. By throttling the updates, you can avoid unnecessary re-renders and improve the overall performance of your React application.
Note: The actual implementation of the hook (useThrottle
) is not shown in this example, but it ensures that the throttleValue
is updated only at the specified interval and reflects the latest value of value
.