useThrottle

useThrottle

useThrottle is a custom React hook that helps in limiting the rate at which a function can be executed. It receives two arguments, value and delay and returns the throttled value.

Props

  • value: The value that needs to be throttled.

  • delay: (optional) The minimum interval, in milliseconds, between two consecutive executions of the function. The default value is 5000 milliseconds.

Returns

The useThrottle hook returns the throttled value.

The Hook

useThrottle.ts
import { useEffect, useRef, useReducer } from "react";
 
export const useThrottle = <T>(value: T, delay: number = 5000): T => {
  const [throttledValue, setThrottledValue] = useReducer(
    (_prev: T, next: T) => next,
    value
  );
  const lastExecutionTime = useRef<number>(Date.now());
 
  useEffect(() => {
    if (Date.now() >= lastExecutionTime.current + delay) {
      lastExecutionTime.current = Date.now();
      return setThrottledValue(value);
    }
    const timerId = setTimeout(() => {
      lastExecutionTime.current = Date.now();
      setThrottledValue(value);
    }, delay);
    return () => clearTimeout(timerId);
  }, [value, delay]);
 
  return throttledValue;
};

Usage

UseThrottleDemo.tsx
import React, { useState, ChangeEvent } from "react";
import { useThrottle } from "./useThrottle";
 
export const UseThrottleDemo = () => {
  const [searchParam, setSearchParam] = useState<string>("");
 
  const searchDebounce = useThrottle(searchParam, 400);
 
  const handlerSearch = (event: ChangeEvent<HTMLInputElement>) => {
    setSearchParam(event.target.value);
  };
 
  return (
    <div>
      <h1>useThrottle hook demo</h1>
      <input type="text" onChange={handlerSearch} />
      <p>Without throttle :{searchParam}</p>
      <p>Throttled Value :{searchDebounce}</p>
    </div>
  );
};