Throttle gif search by 500ms (#3622)
* debounce gif search by 300ms * Throttle it instead --------- Co-authored-by: Dan Abramov <dan.abramov@gmail.com>
This commit is contained in:
parent
8b33ffdfb5
commit
edbb18afa4
2 changed files with 30 additions and 8 deletions
27
src/components/hooks/useThrottledValue.ts
Normal file
27
src/components/hooks/useThrottledValue.ts
Normal file
|
@ -0,0 +1,27 @@
|
|||
import {useEffect, useRef, useState} from 'react'
|
||||
|
||||
import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback'
|
||||
|
||||
export function useThrottledValue<T>(value: T, time?: number) {
|
||||
const pendingValueRef = useRef(value)
|
||||
const [throttledValue, setThrottledValue] = useState(value)
|
||||
|
||||
useEffect(() => {
|
||||
pendingValueRef.current = value
|
||||
}, [value])
|
||||
|
||||
const handleTick = useNonReactiveCallback(() => {
|
||||
if (pendingValueRef.current !== throttledValue) {
|
||||
setThrottledValue(pendingValueRef.current)
|
||||
}
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const id = setInterval(handleTick, time)
|
||||
return () => {
|
||||
clearInterval(id)
|
||||
}
|
||||
}, [handleTick, time])
|
||||
|
||||
return throttledValue
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue