Drop-in replacement for `useState` with throttling capabilities. Access local state immediately while dispatching data to worker functions at a throttled rate.
npm install --save use-throttled-state
useThrottledState
allows you to easily work with data locally while dispatching any updates to a worker function in the background. The worker function is only called once per throttleRate
time interval.
Here is a quick writeup with examples!
Interface:
import useThrottledState from "use-throttled-state"
const [value, setValue] = useThrottledState(
initialValue,
throttleRate, // In milliseconds
workerFunction
)
Example with 500 ms throttleRate
:
import React from "react"
import useThrottledState from "use-throttled-state"
const doWork = (query) => {
//... do expensive work with the query ...
db.query(query)
}
const Example = () => {
const [searchQuery, setSearchQuery] = useThrottledState("", 550, doWork)
return (
<>
<input
id="query"
onChange={(event) => {
setSearchQuery(event.target.value)
}}
value={searchQuery}
/>
<div>Local data: {searchQuery}</div>
</>
)
}
A common scenario is wanting to limit the number of context updates that occur as a user types. This setup might look like:
import useThrottledState from "use-throttled-state"
...
const { setValueFromContext, valueFromContext } = useContext(SomeContext)
const [localValue, setLocalValue] = useThrottledState(
valueFromContext,
500,
(newValue) => {
setValueFromContext(newValue)
}
)
MIT © @patrickDesign
This hook is created using create-react-hook.