hill2hill3hill4hill5treeleafplant
logo

Dev Capture

React throttling

calendar6/4/2025

play
  • REACT

Throttling is a technique, where a given function runs only once at a specified period of time

Throttling could be used in scenarios, where our code does expensive CPU/Network tasks on frequently fired events:

  • Listening to HTML Input element change
  • Listening to window resize or scroll
  • Listening to mouse cursor position change
import { useEffect, useRef, useState } from 'react'

function useThrottle<T>(value: T, interval = 500): T {
  const [throttledValue, setThrottledValue] = useState<T>(value)
  const lastExecuted = useRef<number>(Date.now())

  useEffect(() => {
    if (Date.now() >= lastExecuted.current + interval) {
      lastExecuted.current = Date.now()
      setThrottledValue(value)
    } else {
      const timerId = setTimeout(() => {
        lastExecuted.current = Date.now()
        setThrottledValue(value)
      }, interval)

      return () => clearTimeout(timerId)
    }
  }, [value, interval])

  return throttledValue
}