React Developer interview question · Most asked

Write a custom React hook that debounces a value, and use it to search an API without race conditions.

Hands-on Asked in Frontend Engineer · Full Stack Engineer interviews

Members can save this page, take notes and track progress. See membership · Sign in

Summary

A useDebouncedValue hook stores the latest value after it has stopped changing for a delay. The search effect then runs on the debounced value and cancels the previous request with an AbortController, so a slow earlier response can't overwrite a newer one.

Longer Answer

Points to explain: the cleanup function clears the timer and aborts the fetch; ignore AbortError; in real apps TanStack Query handles caching, cancellation and deduplication for you (queryKey: ["search", debounced]).

Example

import { useEffect, useState } from "react";

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

export function Search() {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<string[]>([]);
  const debounced = useDebouncedValue(query);

  useEffect(() => {
    if (!debounced) return setResults([]);
    const controller = new AbortController();
    fetch(`/api/search?q=${encodeURIComponent(debounced)}`, { signal: controller.signal })
      .then((r) => r.json())
      .then(setResults)
      .catch((e) => { if (e.name !== "AbortError") console.error(e); });
    return () => controller.abort();
  }, [debounced]);

  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Search" />
      <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>
    </>
  );
}

Key Points

  • Timer cleanup on every change.
  • AbortController cancels stale requests.
  • Ignore AbortError.
  • TanStack Query solves this in production code.

Explanation

What interviewers look for

Correct effect cleanup and awareness of race conditions.

More React Developer questions

← All React Developer questions

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake