Rooks
Performance & Optimization

useThrottle

Throttles a callback so it executes at most once per specified time interval.

About

Throttle custom hook for React

Examples

Basic usage

import React, { useState } from "react";
import { useThrottle } from "rooks";

function App() {
  const [text, setText] = useState("");
  const [throttleValue, setThrottleValue] = useState("");
  const [throttledFunction, isReady] = useThrottle(setThrottleValue, 1000);

  return (
    <div>
      <h1>Rooks : useThrottle example</h1>
      <input
        onChange={e => {
          setText(e.target.value);
          throttledFunction(e.target.value);
        }}
      />
      <p>Actual value: {text}</p>
      <p>
        Throttled value (being updated at most once per second): {throttleValue}
      </p>
    </div>
  );
}

export default App;

Arguments

ArgumentTypeDescriptionDefault value
callback (required)FunctionFunction that needs to be throttledundefined
timeout (optional)NumberTime to throttle the callback in ms300

Return value

Return valueTypeDescription
throttledFunctionFunctionA throttled function that will run at most once per timeout ms
isReadyBooleanTells whether calling throttledFunction at that point will fire or not

Robustness and lifecycle

The throttle gate closes synchronously before invoking the callback, so repeated calls in the same event or React batch still execute at most once. The returned function remains stable and invokes the latest callback.

On this page