Search Box in the URL
Medium · Search Params
A search that lives only in useState is lost on reload and cannot be shared. Store it in the URL (/?q=ap) instead, and let the list read it from there, so the URL is the single source of truth.
- useRouter().replace(url) changes the URL **without** adding a history entry. Use it for typing, otherwise every keystroke would need its own Back click.
- useSearchParams() is read-only: copy it with new URLSearchParams(searchParams) before calling set / delete.
Update SearchBox:
- On every change of the input, call router.replace with the new URL: keep other params, set("q", value), or delete("q") when the input is empty. Build the URL from usePathname() (pathname + "?" + query, or just pathname when the query is empty).
- The list shows the fruits whose name contains q (from the URL), ignoring case.
- Opening /?q=an directly filters the list. Starting the input with defaultValue={searchParams.get("q") ?? ""} makes a reload show the text too (the pattern of the official Next.js tutorial).
(Real apps usually debounce this so the server is not asked on every keystroke.)
Next: Sort Select in the URL