Files
bsky-social-app/src/components/hooks/useThrottledValue.ts
T
dan 27bb383268 Submit fix (#4978)
* Fix submit logic

* Fix type

* Align submit task creation 1:1 with callsites

* blegh. `useThrottledValue`

* make `useThrottledValue`'s time required

---------

Co-authored-by: Hailey <me@haileyok.com>
2024-08-22 22:43:23 +01:00

28 lines
696 B
TypeScript

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
}