From edbb18afa44bcfee4560ac19880a0c32563b6a0e Mon Sep 17 00:00:00 2001 From: Samuel Newman Date: Fri, 19 Apr 2024 22:55:53 +0100 Subject: Throttle gif search by 500ms (#3622) * debounce gif search by 300ms * Throttle it instead --------- Co-authored-by: Dan Abramov --- src/components/hooks/useThrottledValue.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/components/hooks/useThrottledValue.ts (limited to 'src/components/hooks/useThrottledValue.ts') 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(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 +} -- cgit 1.4.1