Deviopath › Next.js

Debounced Search in the URL

Hard · Search Params

Build a search box that writes the query to the URL (?q=), but only after the user stops typing for 150 ms. Updating the URL on every keystroke would re-render the page (and in a real app refetch Server Components) for every letter.

- The input is <input className="search" />. It keeps its own local state so typing feels instant.

- Debounce: every change restarts a 150 ms timer. When the timer fires, update the URL with router.replace (typing should not create history entries). Clear the pending timer in the effect cleanup, so fast typing produces a single URL update with the last value.

- The value written to the URL is trimmed. An empty value removes q. All other params are kept.

- While the trimmed input differs from the q in the URL, show <p className="status">Searching…</p>. Typing back to the current value means nothing is pending (and nothing is written).

- The results come from the URL, not from the input: every fruit whose name contains q (case-insensitive) as an <li> in <ul className="results">. No q means all fruits.

- The input starts with the q from the URL, and when q changes from outside (a link, the back button) the input shows the new value.

Next: next build Route Summary