diff options
author | Samuel Newman <mozzius@protonmail.com> | 2024-04-19 22:55:53 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-04-19 22:55:53 +0100 |
commit | edbb18afa44bcfee4560ac19880a0c32563b6a0e (patch) | |
tree | c8b9223c7751d9c8a587477f3087ed764be640a3 /src/components/hooks/useThrottledValue.ts | |
parent | 8b33ffdfb5ca606708c8104ecad4fa5430268483 (diff) | |
download | voidsky-edbb18afa44bcfee4560ac19880a0c32563b6a0e.tar.zst |
Throttle gif search by 500ms (#3622)
* debounce gif search by 300ms * Throttle it instead --------- Co-authored-by: Dan Abramov <dan.abramov@gmail.com>
Diffstat (limited to 'src/components/hooks/useThrottledValue.ts')
-rw-r--r-- | src/components/hooks/useThrottledValue.ts | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/src/components/hooks/useThrottledValue.ts b/src/components/hooks/useThrottledValue.ts new file mode 100644 index 000000000..5764c547e --- /dev/null +++ b/src/components/hooks/useThrottledValue.ts @@ -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 +} |