Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 132 ยท Projects

Project: Search with Debounce and Suspense

Build a search-as-you-type interface in React: see why naive fetching shows stale results, then fix it with a debounce hook, cleanup, a promise cache, Suspense and useDeferredValue.

Search-as-you-type looks like the easiest feature in the world: an input, a list, and a request on every key press. It is also one of the best places to learn how asynchronous React really works, because the obvious version is wrong in a way you can see. Responses come back in a different order than the requests were sent, the server is hit far more often than needed, and the screen flickers through loading states.

In this project you will build the naive version first and watch it fail, then repair it in three layers: a debounce so you wait for the user to pause, cancellation so an old response can never overwrite a newer one, and finally Suspense with a cache so loading is described declaratively instead of with status flags. You should be comfortable with Effects, effect cleanup, custom hooks, and the lessons on the use hook and Suspense and transitions.

The simulated API

Our sandbox allows no network, so we write a fake search function that behaves like a real server: it returns a promise and takes time. To make timing mistakes obvious, the delay depends on the query length. Short queries are slower (a short word matches many items), and queries of three letters or more are fast. Real services behave like this too: response time is not tied to the order of the requests.

JavaScript
function searchFruits(query) {
  console.log('request: "' + query + '"');
  const delay = 400 - 100 * Math.min(query.length, 3);
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(FRUITS.filter((name) => name.includes(query.toLowerCase())));
    }, delay);
  });
}

For a query of one letter the delay is 300 ms, for two letters 200 ms, and for three or more 100 ms. We use short fixed delays so the examples stay quick and predictable. The FRUITS array holds 25 fruit names; you will see it in the code below.

Step 1: the naive version, which is wrong on purpose

The first version does exactly what most people would write: in the onChange handler, store the text and start a request; when the promise settles, store the results. It also records which query the results belong to, so the bug is visible on screen.

Type pea quickly (or click into the input and type it letter by letter without pausing). Three requests start, for p, pe and pea. The last request answers first (100 ms) and the first request answers last (300 ms), so when everything settles the list shows the results for p, while the input says pea.

Stage 1: naive search with a race condition (fails on purpose)

Open the console panel after typing. You will see three request: lines, then three response arrived lines in the order pea, pe, p. The older, slower response overwrote the newer one. This is called a race condition, and it is the most common bug in hand-written data fetching. The user sees results that do not match what they typed, and there is no error to warn them.

There is a second problem hidden in the log: we sent three requests for what the user thought of as one search. On a real server, with thousands of users, that is wasteful.

Step 2: debounce, then ignore stale responses

Debouncing means "wait until the value stops changing for a short time, then use it". Instead of reacting to every key press, we react to the value after the user paused. In React the cleanest way is a small custom hook that returns a delayed copy of a value:

JSX
function useDebouncedValue(value, delayMs) {
  const [debounced, setDebounced] = useState(value);

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

  return debounced;
}

Walk through it. Each time value changes, React runs the cleanup of the previous Effect (which cancels the old timer) and then runs the Effect again (which starts a new timer). Only if value stays unchanged for delayMs does the timer fire and update debounced. Fast typing keeps cancelling the timer, so debounced stays still until the user pauses.

Debouncing reduces the number of requests, but it does not remove the race. If the user types p, pauses 300 ms (request 1 starts and is slow), then types pe, request 1 can still answer after request 2. So the search Effect also needs cancellation. The standard pattern is a local ignore flag set by the cleanup function:

JSX
useEffect(() => {
  let ignore = false;
  searchFruits(debounced).then((found) => {
    if (!ignore) {
      setResults(found);
    }
  });
  return () => {
    ignore = true;
  };
}, [debounced]);

When debounced changes, the cleanup of the previous run executes first and flips that run's own ignore to true. If its promise answers later, the if skips the update. Every Effect run has its own closure, so there is no shared variable to get confused. Real fetch calls can additionally be aborted with an AbortController; the ignore flag works for any promise (data fetching covers both).

In development with <StrictMode>, React mounts, unmounts and mounts every component once to expose missing cleanup. A search Effect with an ignore flag survives this: the first run is ignored, the second run's result is used. It may send one extra request in development only.

Now put both pieces together. The component also tracks a status so it can show "Searching..." and a friendly message for no matches, and it skips the request entirely for an empty query.

Stage 2: debounce plus an ignore flag

Type pea quickly: the console shows a single request: "pea" instead of three. Now type p, wait for a moment, and type e before the first answer arrives: the log shows two requests, and the stale response is dropped with ignored a stale response.

This version works, and it is the one you will find in countless codebases. Its weakness is size: look at how much code (status, results, ignore, the empty-query branch) exists only to manage asynchrony. Every screen that loads data would repeat it.

Step 3: Suspense and a promise cache

React can take that bookkeeping off your hands. A component can call use(promise); if the promise has not resolved, React suspends the component, shows the nearest <Suspense> fallback, and re-renders when the data arrives. There is no status variable and no ignore flag: a component that renders is a component that has its data.

There is one rule you must respect: use needs the same promise object on every render, otherwise each render creates a new request and suspends forever. So we keep a cache that maps a query to its promise, outside any component:

JSX
const cache = new Map();

function getResults(query) {
  if (!cache.has(query)) {
    cache.set(query, searchFruits(query));
  }
  return cache.get(query);
}

Caching also gives a free bonus: typing pe, then backspacing and typing pe again is instant, and the log shows no second request.

The remaining question is the user experience. If the input value goes straight into <Results query={query} />, every new letter suspends and the whole list is replaced by the fallback, causing flicker. We want to keep showing the old results while the new ones load. useDeferredValue does exactly that: it gives the input the new value immediately, but gives Results the old value until the new render can complete without suspending. Comparing the two values tells us when we are showing stale data, so we can dim the list.

Stage 3: Suspense, use and useDeferredValue

Try this experiment: type pe, wait for the results, then type one more letter. The old list stays visible at half opacity until the new one is ready, instead of vanishing behind "Searching...". The fallback shows only on the very first search, when there is nothing old to show. Then delete the last letter again: the result for pe is already in the cache, and appears with no new request line in the console.

This cache never expires and never handles errors. A rejected promise stored in it would make every render of that query throw, and you need an error boundary around Suspense to show a message (error boundaries). Real applications use a library that adds expiry, retries and invalidation; caching and server state builds a small version of one.

Step 4: put it all together

The Suspense version still sends a request for every intermediate value that React decides to render (p, pe, pea). Layering debouncing on top reduces that: the deferred part keeps the UI smooth, and the debounce part saves the network. Combine the hook from step 2 with the components from step 3:

  1. The input is controlled by query, so typing is always instant.
  2. debouncedQuery = useDebouncedValue(query, 250) only changes after a pause.
  3. deferredQuery = useDeferredValue(debouncedQuery) keeps the old list on screen while a new one loads.
  4. Results reads from the cache with use.

You also get to decide what "stale" means. The list is dimmed when the user is still typing (query !== debouncedQuery) or the new results have not arrived (debouncedQuery !== deferredQuery).

Stage 4: debounce, deferred value and cache together

Notice the small improvements: the query is normalized (trimmed, lowercase) before it reaches the cache, so Pea and pea share an entry; the status line uses role="status" so assistive technology can announce updates; and the results show a count.

Which technique for which job?

Problem Tool
Too many requests while typing Debounce (useDebouncedValue)
An old response overwriting a new one Cleanup with an ignore flag or AbortController
Boilerplate loading flags Suspense + use
Flicker when results change useDeferredValue or a transition
Repeat queries hitting the server A cache (or a data library)

Do not stack every tool just because you can. A local list filtered in memory needs none of this: items.filter(...) during render is instant, and a deferred value is enough if rendering is heavy. Debounce and cancellation matter when a request is involved.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the naive search, why can the list show results for 'p' while the input says 'pea'?

    Nothing guarantees that responses arrive in request order. Without cancellation the slowest, oldest response runs last and overwrites newer results.
  2. 2. How does useDebouncedValue avoid reacting to every keystroke?

    The Effect's cleanup clears the previous setTimeout. Only an uninterrupted timer reaches setDebounced.
  3. 3. What does the ignore flag in the search Effect protect against?

    The cleanup of an Effect run sets that run's own ignore variable to true. If its promise settles later, the result is discarded.
  4. 4. Why must use(promise) receive a cached promise rather than calling searchFruits(query) directly in render?

    use waits for the promise it is given. If every render creates a fresh promise, the component suspends forever. A cache keyed by query returns the same promise object each time.
  5. 5. What does useDeferredValue(query) do in the Suspense version?

    The input uses the live value, while Results receives the older deferred value until the new render can finish without showing a fallback. It does not cancel or delay network requests.

Summary

  • Fire-and-forget fetching in onChange has a race condition: responses may arrive out of order and an old one can overwrite a new one.
  • Debounce with a small hook: an Effect starts a timer, its cleanup cancels the previous one, and only a quiet period updates the value.
  • Cancel stale work in the Effect cleanup, with an ignore flag for any promise or an AbortController for fetch.
  • Suspense plus use(promise) removes loading flags, but the promise must be stable, so cache it outside the component (and add an error boundary).
  • useDeferredValue keeps the previous results on screen while new ones load; compare the live and deferred values to dim stale content.
  • Normalize the query before using it as a cache key, and use a real data library when you need expiry, retries or invalidation.

Next: Project: Markdown Notes App