Free 20-minute strategy call with a senior engineer: AI, payments, eLearning or custom software
Engineering

How to Debounce and Throttle a Callback with React Hooks

How to Debounce/Throttle a Callback with React Hooks

Key takeaways

  • Create the debounced or throttled function once per component, keep the latest callback in a ref, and cancel the timer on unmount.
  • Debounce waits until events stop (search, autosave); throttle runs at most once per interval (scroll, resize, drag).
  • React Strict Mode runs an extra effect setup and cleanup in development, so hooks without cleanup show duplicate calls.
  • For slow rendering, use useDeferredValue or useTransition; keep debounce and throttle for network requests and other side effects.

To debounce or throttle a callback in React, create the debounced function once per component (with useMemo or a custom hook), keep the latest callback in a ref so the timer never calls stale code, and cancel any pending timer when the component unmounts. Debounce waits until events stop (search boxes, autosave); throttle runs at most once per interval (scroll, resize, drag).

The most common bug is creating a new debounced function on every render, which resets the timer each time and means nothing is ever debounced. This guide gives you two small hooks, useDebouncedCallback and useThrottledCallback, with cancel and flush, a debounced search example, notes on React 19 and Strict Mode, and when to use useDeferredValue, useTransition or a library instead. The examples use TypeScript and React 19.3, the current release at the time of writing (see React versions); they also work in React 18.

Debounce vs throttle: which one do you need?

Both limit how often a function runs, but they answer different questions. Debounce asks “has the user stopped?”; throttle asks “has enough time passed since the last run?”

TechniqueWhat it doesUse it for
DebounceRuns once, after events stop for n millisecondsSearch-as-you-type, autosave, form validation, window resize end
ThrottleRuns at most once every n milliseconds while events continueScroll position, infinite scroll, drag, mouse move, analytics pings
useDeferredValueLets React render a slow part of the UI with a slightly older value, interruptiblyFiltering or rendering a large list in the browser
useTransitionMarks a state update as non-urgent so input stays responsiveSwitching tabs or views that render heavy content

A simple rule: if the expensive work is a network request or another side effect, debounce or throttle it. If the expensive work is rendering, start with useDeferredValue or useTransition, which are covered further down.

Why the naive approach fails

Each render of a function component creates new local functions. If you write const debounced = debounce(search, 300) directly in the component body, every keystroke causes a render, every render creates a new debounced function with its own timer, and every call goes through a fresh timer. You get one request per keystroke, just delayed.

Wrapping the callback in useCallback with the callback and delay as dependencies (as many older tutorials do) has a quieter version of the same problem: whenever the parent passes a new callback, the hook returns a new function, and any code that compares it (effect dependencies, memo children) re-runs. A correct hook needs three things:

  • A stable function identity that survives re-renders, created with useMemo and recreated only when the delay changes.
  • A ref to the latest callback, so the timer always calls current code with current props and state, without restarting.
  • Cleanup that cancels the pending timer when the component unmounts, so you never update state on an unmounted component or fire a request nobody needs.

A correct useDebouncedCallback hook

This hook returns a debounced function with cancel(), flush() and isPending() methods, the same shape as the popular libraries:

import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';

type AnyFn = (...args: any[]) => void;

export function useDebouncedCallback<T extends AnyFn>(callback: T, delay: number) {
  const callbackRef = useRef(callback);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const argsRef = useRef<Parameters<T> | null>(null);

  // Keep the latest callback without restarting the timer
  useLayoutEffect(() => {
    callbackRef.current = callback;
  });

  const debounced = useMemo(() => {
    const cancel = () => {
      if (timerRef.current !== null) clearTimeout(timerRef.current);
      timerRef.current = null;
      argsRef.current = null;
    };

    // Run the pending call now (for example before navigating away)
    const flush = () => {
      if (timerRef.current === null || argsRef.current === null) return;
      const args = argsRef.current;
      cancel();
      callbackRef.current(...args);
    };

    const fn = (...args: Parameters<T>) => {
      argsRef.current = args;
      if (timerRef.current !== null) clearTimeout(timerRef.current);
      timerRef.current = setTimeout(flush, delay);
    };

    return Object.assign(fn, { cancel, flush, isPending: () => timerRef.current !== null });
  }, [delay]);

  // Cancel the pending call on unmount (and when the delay changes)
  useEffect(() => debounced.cancel, [debounced]);

  return debounced;
}

The callback ref is updated in useLayoutEffect rather than during render, because React’s rules say you should not write to ref.current while rendering (see the useRef reference). Layout effects run after the commit and before the browser paints, so the ref is current before the user can trigger another event.

A correct useThrottledCallback hook

This throttle runs immediately on the first call (leading edge), ignores calls inside the window, and then runs once more at the end of the window with the latest arguments (trailing edge), so the final scroll or drag position is never lost:

export function useThrottledCallback<T extends AnyFn>(callback: T, wait: number) {
  const callbackRef = useRef(callback);
  const lastRunRef = useRef(0);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const argsRef = useRef<Parameters<T> | null>(null);

  useLayoutEffect(() => {
    callbackRef.current = callback;
  });

  const throttled = useMemo(() => {
    const run = () => {
      timerRef.current = null;
      lastRunRef.current = Date.now();
      const args = argsRef.current;
      argsRef.current = null;
      if (args) callbackRef.current(...args);
    };

    const cancel = () => {
      if (timerRef.current !== null) clearTimeout(timerRef.current);
      timerRef.current = null;
      argsRef.current = null;
    };

    const flush = () => {
      if (timerRef.current === null) return;
      clearTimeout(timerRef.current);
      run();
    };

    const fn = (...args: Parameters<T>) => {
      argsRef.current = args;
      const remaining = wait - (Date.now() - lastRunRef.current);
      if (remaining <= 0) {
        if (timerRef.current !== null) clearTimeout(timerRef.current);
        run(); // leading edge
      } else if (timerRef.current === null) {
        timerRef.current = setTimeout(run, remaining); // trailing edge
      }
    };

    return Object.assign(fn, { cancel, flush });
  }, [wait]);

  useEffect(() => throttled.cancel, [throttled]);

  return throttled;
}

Use it for continuous events. Because the returned function is stable, the effect below subscribes once instead of re-subscribing on every render:

function ScrollProgress() {
  const [progress, setProgress] = useState(0);

  const onScroll = useThrottledCallback(() => {
    const max = document.documentElement.scrollHeight - window.innerHeight;
    setProgress(max > 0 ? window.scrollY / max : 0);
  }, 100);

  useEffect(() => {
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [onScroll]);

  return <progress value={progress} max={1} />;
}

Free resource

Upgrade and patching checklist

Want this applied to your project? Our engineers will send it with notes for your stack.

Get it free

Example: a debounced search box that handles stale responses

Debouncing reduces the number of requests, but it does not stop an older, slower response from arriving after a newer one. Pair the debounce with an AbortController so only the latest request can update state:

type Product = { id: string; name: string };

function ProductSearch() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<Product[]>([]);
  const controllerRef = useRef<AbortController | null>(null);

  const search = useDebouncedCallback(async (q: string) => {
    controllerRef.current?.abort();
    if (!q.trim()) {
      setResults([]);
      return;
    }
    const controller = new AbortController();
    controllerRef.current = controller;
    try {
      const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, {
        signal: controller.signal,
      });
      setResults(await res.json());
    } catch (err) {
      if ((err as Error).name !== 'AbortError') console.error(err);
    }
  }, 300);

  // Abort an in-flight request on unmount
  useEffect(() => () => controllerRef.current?.abort(), []);

  return (
    <>
      <input
        value={query}
        onChange={(e) => {
          setQuery(e.target.value); // the input stays instant
          search(e.target.value);   // the request is debounced
        }}
        placeholder="Search products"
      />
      <ul>
        {results.map((p) => <li key={p.id}>{p.name}</li>)}
      </ul>
    </>
  );
}

Two details matter. The input’s own state updates on every keystroke, so typing never feels laggy; only the request is delayed. And the value is passed to the debounced function rather than the event object, which keeps the callback independent of React’s event system. Between 250 and 500 ms is a common delay for search; tune it with real users.

Alternative: debounce the value instead of the callback

If you would rather keep the fetch inside an effect (or in a data library such as TanStack Query keyed by the search term), debounce the value. This version is short and naturally safe in Strict Mode because the effect cleans up its own timer:

function useDebouncedValue<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);
  }, [value, delay]);
  return debounced;
}

// const debouncedQuery = useDebouncedValue(query, 300);
// useEffect(() => { /* fetch with debouncedQuery */ }, [debouncedQuery]);

How React 19 and Strict Mode affect debounced callbacks

In development, Strict Mode renders components twice and runs one extra setup and cleanup cycle for every Effect. That is why both hooks above cancel in an effect cleanup: the extra cycle simply cancels a timer that does not exist yet, and nothing leaks. If a debounce hook has no cleanup, Strict Mode is often where you first see duplicate requests or warnings.

  • Memoised values are reused in the double render. The React 19 upgrade guide notes that useMemo and useCallback reuse the first render’s result during Strict Mode’s second render, so the debounced function is not created twice.
  • Do not treat useMemo as a guarantee. React may discard memoised values in some cases. The hooks above keep the timer and arguments in refs and cancel the old instance in cleanup, so a recreated function still behaves correctly.
  • Hydration now double-invokes Effects too. React 19.3 runs Strict Mode’s extra Effect cycle during hydration, matching client-rendered roots (see the React 19.3 post). Server-rendered apps that skipped this check before may now surface missing cleanups.
  • useEffectEvent is not a replacement here. It shipped in React 19.2 (see the React 19.2 post), but the docs say an Effect Event may only be called from inside Effects, not from event handlers or children. A debounced onChange handler still needs the ref pattern.

When to use useDeferredValue or useTransition instead

If typing feels slow because a large list re-renders on each keystroke, a debounce only moves the freeze to later. The useDeferredValue documentation explains why: deferred re-renders need no fixed delay, adapt to the device, and are interruptible, while debounced and throttled renders still block once they start. The docs also say debouncing and throttling remain useful when the work does not happen during rendering, such as limiting network requests, and that you can combine them.

function FilterableList({ items }: { items: Item[] }) {
  const [text, setText] = useState('');
  const deferredText = useDeferredValue(text);
  const isStale = text !== deferredText;

  return (
    <>
      <input value={text} onChange={(e) => setText(e.target.value)} />
      <div className={isStale ? 'dimmed' : undefined}>
        <SlowList items={items} filter={deferredText} />
      </div>
    </>
  );
}
// Wrap SlowList in memo() so it only re-renders when deferredText changes.

Use useTransition when you own the state update and want to mark it as non-urgent, for example switching to a tab that renders a heavy chart. For a search box that both filters local data and calls an API, a common combination is useDeferredValue for the list and a debounced callback for the request.

Library options: use-debounce and lodash

Writing your own hook is fine for a few call sites, but a maintained library covers edge cases such as maxWait and leading-only behaviour.

OptionWhat you getNotes
use-debounceuseDebounce (value), useDebouncedCallback and useThrottledCallback, with cancel, flush and isPendingHook-first, small; options leading, trailing and maxWait. Version 10.1 at the time of writing
lodash debounce and throttleBattle-tested functions with cancel and flushNot React-aware: create once with useMemo, call the latest callback through a ref and cancel on unmount
Your own hook (above)Exactly the behaviour you need, no dependencyYou maintain and test it

With use-debounce, the search example becomes:

import { useDebouncedCallback } from 'use-debounce';

const search = useDebouncedCallback((q: string) => runSearch(q), 300, { maxWait: 1000 });
// search.cancel(), search.flush() and search.isPending() are available

If you use lodash, import the single function (import debounce from 'lodash/debounce' or the lodash-es build) so your bundler can drop the rest. The standalone lodash.debounce package still works but has not been republished since 2016, so the main lodash package is the better-maintained source.

Common mistakes checklist

  • Calling debounce() directly in the component body, which creates a new timer every render.
  • Putting the callback in the hook’s dependency list, which recreates the debounced function whenever the parent re-renders.
  • No cleanup on unmount, which leads to state updates on unmounted components and wasted requests.
  • Debouncing the input’s own value, which makes typing feel broken. Keep the input instant and debounce the side effect.
  • Ignoring out-of-order responses. Use AbortController or a request ID.
  • Using debounce to hide slow rendering. Profile first, then try useDeferredValue, memo or list virtualisation.

Frequently asked questions

What is the difference between debounce and throttle in React?

Debounce runs a function once, after events have stopped for a set time. Throttle runs it at most once per interval while events keep firing. Use debounce for search and autosave, and throttle for scroll, resize and drag.

Why is my debounced function not working in React?

Usually because a new debounced function is created on every render, so each call gets its own timer. Create it once with useMemo or a custom hook, and read the latest callback from a ref.

Should I use useCallback or useMemo to debounce?

useMemo(() => debounce(fn, delay), [delay]) expresses the intent best, because you are memoising the result of calling debounce. Pair it with a ref to the latest callback and a cleanup that cancels on unmount, or use a library hook that does this for you.

Does React Strict Mode break debounce?

No, but it exposes missing cleanup. In development, Strict Mode runs an extra setup and cleanup for every Effect. If your hook cancels its timer in cleanup, behaviour is correct in both development and production.

Is useDeferredValue better than debounce?

For slow rendering, usually yes: it needs no fixed delay and is interruptible. For network requests and other side effects, debounce or throttle is still the right tool. Many search screens use both.

Need a faster, more reliable React front end?

Vibidsoft builds and fixes React and Next.js applications as fixed-price work, never by the hour. A fixed-price assessment (from $1,500, credited to the build) profiles your slow screens, request patterns and re-renders and gives you a written fix list with a fixed quote. Larger work runs as milestone projects with acceptance criteria, or as an outcome pod from $4,000/month for ongoing product work.

See our React development services, browse more engineering guides, or book a free 20-minute call.

Vibidsoft Engineering Team

Senior engineers who have shipped 450+ projects since 2014 across AI, payments, eCommerce, eLearning and custom software. Every guide is written and reviewed by the people who do the work.

Follow us on LinkedIn · About Vibidsoft

Next step

Talk to an engineer about Modernize & Rescue

Fixed-price upgrades for ageing PHP, Drupal, Magento or hybrid apps, with security patching and a care plan. from $5,000.

  • A 20-minute call with a senior engineer, not a salesperson
  • A written next-step plan within one business day
  • NDA on request
Book a call WhatsApp