DEV Community

Cover image for You're debouncing search input. `useDeferredValue` skips the timer.
Parsa J
Parsa J

Posted on Originally published at bestpractic.org

You're debouncing search input. `useDeferredValue` skips the timer.

Type react into a search box filtering 10,000 rows, and watch the input lag half a beat behind your own keystrokes. Open React DevTools and the component isn't broken — it's doing exactly what you told it to. It's just doing all of it, every time, before it lets the next character land.

The fix half the internet reaches for is a debounce. Wait 300ms after the user stops typing, then filter. It feels like it should work — fewer renders, less work. Try it in a real app and the stutter doesn't go away. It just moves to the end: the box stays suspiciously quiet for 300ms, then the final keystroke drags along a full re-filter of 10,000 rows, and that frame is the one that hitches.

Debounce was never fixing the slow part

Here's the part that's easy to miss: debounce doesn't make a render cheaper. It only makes it less frequent.

function Search({ items }) {
  const [query, setQuery] = useState("");
  const [debounced, setDebounced] = useState("");

  useEffect(() => {
    const id = setTimeout(() => setDebounced(query), 300);
    return () => clearTimeout(id);
  }, [query]);

  // still a synchronous, blocking filter — just a rarer one, thanks to
  // useMemo skipping it on the renders where `debounced` hasn't changed
  const results = useMemo(
    () => items.filter((i) => i.name.includes(debounced)),
    [items, debounced]
  );

  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <List items={results} />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

debounced changes less often than query — that part works. But when it does change, filtering 10,000 rows and re-rendering however many of them matched still happens on the main thread, still blocking, in one synchronous commit. You've traded "stutters on every keystroke" for "freezes for one frame, 300ms after you stop." Neither one is "the input never lags" — and the freeze gets worse the more rows there are to render, not just the more rows there are to filter.

And there's a second cost nobody budgets for: that setTimeout is tracking state that has nothing to do with the server. If items is already in memory — no fetch, no endpoint, nothing to rate-limit — you've added a timer, a cleanup function, and a second piece of state to solve a problem debounce was never built for. Debounce exists to cut down how often a side effect fires. A local array filter isn't a side effect. It's a render.

Before you scroll — what's actually slow here: the filtering, or the fact that it runs on every keystroke?

The fix that doesn't ask you to pick a delay

useDeferredValue is a React hook built for exactly this split: let the input update immediately, every time, and let the expensive thing that depends on it lag behind on purpose.

import { useState, useDeferredValue, memo } from "react";

function Search({ items }) {
  const [query, setQuery] = useState("");
  const deferredQuery = useDeferredValue(query);
  const isStale = query !== deferredQuery;

  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <div style={{ opacity: isStale ? 0.6 : 1 }}>
        <List items={items} query={deferredQuery} />
      </div>
    </>
  );
}

// The filter has to live INSIDE the memoized component, keyed off the
// deferred value — that's what gives memo something stable to bail out on.
// Filtering in Search instead (and just handing List the result) would run
// the expensive work on every keystroke regardless of what's deferred.
const List = memo(function List({ items, query }) {
  const results = items.filter((i) => i.name.includes(query));
  return <ul>{results.map((i) => <li key={i.id}>{i.name}</li>)}</ul>;
});
Enter fullscreen mode Exit fullscreen mode

No setTimeout. No "how many milliseconds feels right." query updates on every keystroke at full priority, so the input itself never lags — React treats typing as urgent and always renders it first. deferredQuery is a separate value that trails behind: React renders the list with the old deferred value first (cheap, since List is memoized and its props haven't changed), then — in the background, interruptible — renders it again with the new one.

That word, interruptible, is the actual mechanism, and it's the thing debounce can't do. If you type a second character before the deferred re-render finishes, React throws away that half-finished background work and starts over with the latest value, instead of finishing a now-stale render first. A debounce timer can't abandon work mid-flight like that — it can only decide when to start it.

Open your profiler and try both versions on a list of a few thousand rows. The debounced one shows long blocking tasks lined up end to end. The deferred one shows the same total filtering work, but broken into renders that each yield back to the browser — the keystroke you just made always wins the next frame.

Where it stops helping

useDeferredValue doesn't make filtering or rendering 10,000 rows faster. If that work takes 40ms, it still takes 40ms somewhere — the hook controls when React is allowed to start and finish that render relative to the next keystroke, and lets it move on to a newer update instead of committing a result that's already stale. If your list still needs virtualization or a better filtering algorithm, you still need to do that work; this just stops an already-reasonable render from fighting the keyboard for priority.

And it isn't a debounce replacement for the case debounce actually exists for: rate-limiting a request. If query drives a fetch to a search endpoint, you still want to wait before firing it — nobody wants an API call per keystroke, and useDeferredValue won't cut that count down, because it's a rendering primitive, not a networking one. Keep debouncing the request. Stop debouncing the render.

The isStale flag is worth keeping even once the lag is gone — not for performance, but for honesty with the reader: a slightly dimmed list for the few milliseconds between "you typed" and "the filtered results landed" tells them the app noticed their keystroke, instead of silently pretending nothing happened.

Next time a search box or a filter panel stutters, check which one you actually have: a request worth delaying, or a render that was never doing it concurrently in the first place.

🎮 Try it yourself

▶️ Open the interactive playground →

Runs right in your browser — poke at it and watch the concept react live.

The part worth keeping

Debounce answers "how often." useDeferredValue answers "what's allowed to interrupt what." They look like the same fix because they both make a laggy search box feel better — but only one of them is actually about rendering, and a search box filtering data you already have is a rendering problem first.

Which search box in your own codebase has a debounce timer guarding a filter that never touches the network? That's the one worth checking first.

🧠 Test yourself

Think it clicked? Take the 7-question quiz →

Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.

📚 Read next


🚀 Want more like this? Every guide, playground, and quiz lives on bestpractic.org — open it and sign up free so the next one finds you.

Thanks for reading! Let's stay connected:

Top comments (1)

Collapse
 
parimalmakes profile image
Parimal Makes •

putting the filter inside the memoized List keyed off deferredQuery is the detail people always miss when they first try useDeferredValue
without memo bailing out on the stale prop it still re-filters on every keystroke anyway