ReactMedium

Debounce in React?

Debouncing delays running a function until a burst of events has stopped for a set time, for example calling a search API only after the user stops typing for 300ms. In React, either debounce the value with a useDebounce hook and use it as an effect or query dependency, or keep a stable debounced function in a ref or memo so it is not recreated every render.

Two approaches

  1. Debounced value: const debouncedQuery = useDebounce(query, 300). The input updates instantly; effects or queries depend on debouncedQuery. Simple and declarative.
  2. Debounced callback: create the debounced function once (useMemo(() => debounce(fn, 300), []) or a useDebouncedCallback hook) and call it from onChange. Cancel it on unmount.

Pitfalls

  • Creating debounce(fn) inline in render makes a new timer every render, so it never debounces.
  • The debounced function captures stale props or state unless it reads the latest values (via a ref, useEffectEvent, or by passing values as arguments).
  • Forgetting to cancel on unmount can fire after the component is gone.
  • Debouncing does not prevent out-of-order responses; still cancel or ignore stale requests.

Debounce vs alternatives

  • useDeferredValue: keeps typing responsive for expensive rendering, but it does not reduce network requests.
  • Throttle: runs at most once per interval during continuous events (scroll, resize).
  • TanStack Query with a debounced key: caches each query and handles cancellation.

Typical delays

200 to 400ms for search; 500ms to 2s for autosave.

Code example

tsx
1import { useEffect, useMemo, useRef, useState } from "react";
2
3export function useDebounce<T>(value: T, delay = 300) {
4 const [debounced, setDebounced] = useState(value);
5 useEffect(() => {
6 const id = setTimeout(() => setDebounced(value), delay);
7 return () => clearTimeout(id); // restart the timer on every change
8 }, [value, delay]);
9 return debounced;
10}
11
12export function useDebouncedCallback<A extends unknown[]>(fn: (...args: A) => void, delay = 300) {
13 const fnRef = useRef(fn);
14 useEffect(() => { fnRef.current = fn; }); // always call the latest fn (no stale closure)
15 const debounced = useMemo(() => {
16 let id: ReturnType<typeof setTimeout> | undefined;
17 const run = (...args: A) => { clearTimeout(id); id = setTimeout(() => fnRef.current(...args), delay); };
18 run.cancel = () => clearTimeout(id);
19 return run;
20 }, [delay]);
21 useEffect(() => debounced.cancel, [debounced]); // cancel on unmount
22 return debounced;
23}
24
25export function Search() {
26 const [query, setQuery] = useState("");
27 const debouncedQuery = useDebounce(query, 300);
28 const [results, setResults] = useState<string[]>([]);
29
30 useEffect(() => {
31 if (!debouncedQuery) return setResults([]);
32 const ctrl = new AbortController();
33 fetch(`/api/search?q=${encodeURIComponent(debouncedQuery)}`, { signal: ctrl.signal })
34 .then((r) => r.json()).then(setResults).catch(() => {});
35 return () => ctrl.abort();
36 }, [debouncedQuery]);
37
38 return (
39 <>
40 <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />
41 <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>
42 </>
43 );
44}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app