diff options
Diffstat (limited to 'src/components/hooks')
-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 +} |