about summary refs log tree commit diff
path: root/src/components/hooks/useThrottledValue.ts
blob: 29a11b93584bbfbd758881393ec160ca10ff2e66 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
}