Mastering the useThrottle Hook in React

Apr 22, 2024

Mastering the useThrottle Hook in React

In this blog, we explore how to control function execution frequency efficiently and learn how to optimize performance with React's useThrottle hook.

Author

Daya
DayaSoftware Engineer III

Subject Matter Expert

Tarun Bhagchand Soni
Tarun Bhagchand SoniSenior Software Engineer - II
Click On The Image Above To Watch How It Works
Click On The Image Above To Watch How It Works

In the fast-paced world of web applications, user interactions can trigger a flurry of events. While responsiveness is crucial, excessive function calls can lead to performance bottlenecks. Enter the useThrottle hook, a powerful tool in React's arsenal for managing execution frequency.


Understanding Throttling

Throttling ensures that a function executes at most once within a specified time interval, regardless of how many times it is called. It is similar to a leaky faucet that only releases water intermittently, preventing a deluge.

Why Use Throttling?

  • Performance Optimization: Throttling prevents repetitive, expensive operations, such as API calls or complex calculations, from overwhelming the browser. This smooths out user experience and enhances application responsiveness.
  • Event Debouncing: It is ideal for scenarios where rapid user input (for example, continuous scrolling, resize events) might trigger unnecessary updates. Throttling ensures they are handled efficiently, minimizing redundant computations.


How Does useThrottle Work?

Let us dissect the provided code:

import { useRef } from 'react';

function useThrottle(cb: () => void, limit: number) {
  const lastRun = useRef(Date.now());

  return function () {
    if (Date.now() - lastRun.current >= limit) {
      cb(); // Execute the callback
      lastRun.current = Date.now(); // Update last execution time
    }
  };
}

Import and Setup:

JavaScript

import { useRef } from 'react';

We import useRef from React to create a reference that persists across re-renders, ideal for tracking the last execution time.

useThrottle Hook Function:

function useThrottle(cb: () => void, limit: number) {
  const lastRun = useRef(Date.now());

  return function () {
    if (Date.now() - lastRun.current >= limit) {
      cb(); // Execute the callback
      lastRun.current = Date.now(); // Update last execution time
    }
  };
}

Parameters:

  • cb: The callback function to be throttled. It takes no arguments and returns nothing (void).
  • limit: The time interval (in milliseconds) between allowed executions.

lastRun Reference:

We create a useRef hook named lastRun to store the timestamp (milliseconds since epoch) of the most recent execution. This ensures the function is called at most once within the specified limit.

Returned Function:

This is the throttled function you will use in your React components. It checks the time difference between the current time (Date.now()) and lastRun.current. If the difference is greater than or equal to limit, it executes the cb function and updates lastRun.current with the current timestamp.



Using useThrottle in React Components

Here is an example of how to use the useThrottle hook in a React component to throttle a scroll event handler:

import { useEffect, useState } from 'react';
import './App.css';
import useThrottle from './hooks/useThrottle';

type Character = {
  id: number;
  name: string;
  image: string;
};

function App() {
  const [data, setData] = useState<Character[] | undefined>([]);
  const [calls, setCalls] = useState(0);
  const [position, setPosition] = useState(0);
  const throttledScroll = useThrottle(handleScroll, 2000);

  function handleScroll() {
    setCalls((c) => c + 1);

    setPosition(
      Math.round(
        ((document.documentElement.scrollTop + document.body.scrollTop) /
          (document.documentElement.scrollHeight -
            document.documentElement.clientHeight)) *
          100
      )
    );
  }

  useEffect(() => {
    fetch(`https://rickandmortyapi.com/api/character`)
      .then((res) => res.json())
      .then((data: { results: Character[] }) => {
        setData(data.results);
      })
      .catch((error) => console.error('Error fetching characters:', error));
  }, []);

  useEffect(() => {
    window.addEventListener('scroll', throttledScroll);
    return () => window.removeEventListener('scroll', throttledScroll);
  }, [throttledScroll]);

  return (
    <div className="container">
      <div className="sticky">
        <p>Calls: {calls}</p>
        <button onClick={() => setCalls(0)}>Reset calls</button>
        <p>Position: {position}%</p>
      </div>
      <div className="character-list">
        {data === undefined && 'Nothing Found.'}
        {data &&
          data.map((character) => (
            <div key={character.id} className="character">
              <img src={character.image} alt={character.name} />
              <div>{character.name}</div>
            </div>
          ))}
      </div>
    </div>
  );
}

export default App;

In this example, the throttledScroll function is created using useThrottle and passed to the scroll event listener. This ensures that the handleScroll function is only called at most every 2000 milliseconds, even if the user scrolls rapidly.

Hire Us Form


Conclusion

The useThrottle hook is a valuable tool for enhancing performance and managing function execution frequency in React applications. By understanding its purpose and implementation, you can make informed decisions about when to use it to improve the responsiveness and efficiency of your web applications.

Subscribe to Our Newsletter

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Insight
Building Local LLMs Using Dart FFI And llama.cpp: Beyond Wrapper Packages
Sep 11, 2026

Building Local LLMs Using Dart FFI And llama.cpp: Beyond Wrapper Packages

Build local LLMs in Flutter with Dart FFI and llama.cpp, and see how native bridges, GGUF models, memory management, and token streaming enable private, on-device AI.

Insight
My Flutter App Froze With Three Photos on Screen. Here's What I Was Doing Wrong
Sep 11, 2026

My Flutter App Froze With Three Photos on Screen. Here's What I Was Doing Wrong

This blog explains how rethinking Flutter’s image-processing architecture fixed severe performance issues and improved rendering efficiency.

Insight
Building a Production-Ready Canva-like Editor with Konva.js, React 19 and Next.js 15
Sep 10, 2026

Building a Production-Ready Canva-like Editor with Konva.js, React 19 and Next.js 15

This blog explains how to build a production-ready canvas editor with Konva.js, React, and Next.js, covering architecture, performance, and key engineering decisions.

Insight
What a PHP-to-NestJS Banking Migration Taught Us About Architecture, Security, and Trust
Sep 8, 2026

What a PHP-to-NestJS Banking Migration Taught Us About Architecture, Security, and Trust

This blog explores the architecture, security, performance, and documentation lessons from migrating a legacy PHP/Laravel banking platform to NestJS.

Insight
Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs
Sep 7, 2026

Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs

This blog explains how to build responsive video thumbnail scrubbing in the browser for local files and HLS streams, covering frame extraction, caching, and performance trade-offs.

Insight
The Agent Can See Your App. How Often Can It Look?
Sep 4, 2026

The Agent Can See Your App. How Often Can It Look?

AI coding agents can now interact with mobile apps, but their effectiveness depends on iteration speed. This blog explores how React Native architecture influences feedback loops and AI-driven developer productivity.

Insight
Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists
Sep 1, 2026

Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists

Learn how to turn design JSON into interactive, video-enabled cards using overlays, smart media controls, caching, and virtualization without slowing down high-cardinality feeds.

The Right Conversation Can

Save You Six Months.

Book a call