FrontendPro

56Implement useDebounce() for values

mediumAbout 35 minutesCodingreacthookstimers

Problem

Implement the hook useDebounce(value, delay). It returns a copy of value that only updates after value has stopped changing for delay milliseconds.

function Search() {
  const [query, setQuery] = useState("");
  const debouncedQuery = useDebounce(query, 300);
  useEffect(() => {
    if (debouncedQuery) searchApi(debouncedQuery); // runs once the user pauses typing
  }, [debouncedQuery]);
  return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}

Requirements

  • Return the initial value immediately on the first render.
  • Every change restarts the wait, so a burst of changes produces a single update with the last value.
  • Clear any pending timer when the component unmounts.
  • If delay changes, use the new delay.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

const [debounced, setDebounced] = useState(value). The initial state is the first value, so nothing waits on the first render.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever