Debounce with search

ReactDebounceSearch25 mins

by Pratik Rai

Read the full write-up

Build a search box that waits for the typing to stop before it searches. Typing "strawberry" should send one request, not ten.

searchFruits(query) is given: it resolves after 400ms and counts how many times it was called.

Requirements

  1. The search runs about 350ms after the last keystroke, not on every keystroke.

  2. A pending search is cancelled when the query changes again.

  3. Clearing the input clears the results without searching.

  4. "Searching…" shows while a request is in flight.

  5. Say so when a search genuinely found nothing — but not before any search has run.

  6. A slow earlier response must not overwrite the results of a later one.

Notes

  • The request counter on screen is there to prove the debounce works: type a long word and it should barely move.

  • Cancelling a real request would use AbortController; here a flag in the effect cleanup is the equivalent.

Hints

Loading editor…