Repository navigation
Unclear how to specify useCallback dependencies for useThrottler() or useThrottledCallback()
#264
|
It looks like referenced values passed to these functions will become stale if they are updated. The docs say: However the |
Replies: 1 comment 1 reply
|
You don't need const [throttler] = useState(() => new Throttler(fn, mergedOptions))
throttler.fn = fn
throttler.setOptions(mergedOptions)and the core The one thing to keep in mind is that there are two sources of values:
So if you need the value as it was at call time, pass it as an argument. If you want the latest value, read it from the closure: const [query, setQuery] = useState('')
const [filters, setFilters] = useState(defaultFilters)
const search = useThrottledCallback(
(q: string) => {
// q: from the call; filters: from the latest render
runSearch(q, filters)
},
{ wait: 300 },
)The same pattern applies to |
You don't need
useCallbackdependencies or refs here: values read inside the callback don't go stale.useThrottlercreates theThrottlerinstance once, but reassigns the function on every render (packages/react-pacer/src/throttler/useThrottler.ts):and the core
Throttlercallsthis.fn(...args)at the moment it executes (packages/pacer/src/throttler.ts,#execute), including the trailing call that fires from the timeout. So whateverfnthe latest render passed in is the one that runs, closing over that render's state and props.useThrottledCallbackis justuseThrottler…