useThrottle
The useThrottle
hook allows you to limit the frequency of a value's change to once every specified interval (defaults to 400ms). This can be especially useful when dealing with fast-changing values, such as those updated in response to user input or external events. The hook helps prevent excessive re-renders and improves performance by ensuring that the value updates are throttled to a specified interval.
Installation
-
Make sure you have
@ridgehkr/useful
installed in your application. If not, you can get started by following the installation instructions. -
Import
useThrottle
into your component.
import { useThrottle } from '@ridgehkr/useful'
Example
This is a basic example where useThrottle
is used to limit the update frequency of a search input's value:
import { ChangeEvent, useState } from 'react'
import { useThrottle } from '@ridgehkr/useful'
function SearchInput() {
const [inputValue, setInputValue] = useState<string>('')
const throttledValue = useThrottle<string>(inputValue, 600)
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value)
}
return (
<div>
<h1>useThrottle</h1>
<p>
<input onChange={handleInputChange} />
</p>
<p>
Throttled input value: <strong>{throttledValue}</strong>
</p>
</div>
)
}
The inputValue
state value is updated whenever the user types in the input field. However, the actual rendering of the throttled value (throttledValue
) will only occur at most once every 600 milliseconds. This prevents excessive re-renders when the user is rapidly typing.
API Reference
Parameters
Property | Type | Description |
---|---|---|
value | T | The value you want to throttle |
interval | number | The interval in milliseconds between updates of the throttled value. Defaults to 400ms. |
Return Value
Property | Type | Description |
---|---|---|
throttledValue | T | The throttled value, which is updated no more frequently than the interval. |