Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 50 ยท Params and Search Params

Putting UI State in the URL

Decide what belongs in the URL and learn the patterns: tabs, sorting, pagination, modals, debounced search, defaults, shareable links and push versus replace.

Every interactive screen has state: which tab is open, how a list is sorted, what the search box says, whether a dialog is showing. By default most developers reach for useState. It works, until a visitor refreshes the page and loses their place, presses Back and leaves the whole page instead of closing the dialog, or sends a colleague a link that opens a different view than the one they were looking at.

Moving the right pieces of state into the URL fixes all three problems at once. The URL becomes a tiny, shareable description of the screen. This lesson is about choosing what goes there and about the patterns that make it pleasant: defaults, resets, push versus replace, debouncing and modals. It builds on Search Params and useSearchParams.

What belongs in the URL?

Ask one question: "If the user refreshed, pressed Back, or shared this link, would they expect this state to survive?" If yes, it probably belongs in the URL.

flowchart TD
  A["A piece of UI state"] --> B{"Should it survive<br/>refresh, Back or sharing?"}
  B -- no --> C["Component state<br/>(useState)"]
  B -- yes --> D{"Small, safe to<br/>show in a link?"}
  D -- no --> E["Server or storage<br/>(session, database)"]
  D -- yes --> F["The URL<br/>(path or search param)"]

A quick decision guide for where to keep a piece of state.

State Usually Why
Which record is open Path param (/orders/42) Identifies a resource
Selected tab Search param (?tab=reviews) or nested route Shareable, Back works
Sort order, filters, page Search params Shareable, survives refresh
Open modal for an item Search param (?item=3) or route Deep link, Back closes it
Text typed in a form field Component state Half-finished input is not a view
Whether a dropdown is open Component state Too transient to share
Login token, personal data Never the URL Leaks into logs and history

A useful rule: path for what you are looking at, search params for how you are looking at it.

Tabs: path or query?

Tabs can be nested routes (/product/7/reviews) or a search param (/product/7?tab=reviews). Use routes when each tab is substantial and has its own data, and a search param when the tabs are light views of the same resource. For a search param, always validate against a whitelist and fall back to a default, because anyone can type ?tab=banana:

JSX
const TABS = ["details", "reviews"];
const raw = searchParams.get("tab");
const tab = TABS.includes(raw) ? raw : "details";

Defaults, resets and clean URLs

Do not write default values into the URL. If "details" is the default tab and "newest" the default sort, then /product/7 already means tab=details&sort=newest. Delete the key instead of setting it to its default. This keeps links short and means the "plain" URL and the "all defaults" URL are the same address, which is also better for caches and analytics.

Be careful with dependent state. When a filter or sort changes, the current page number no longer makes sense (page 4 of the old results may not exist in the new ones), so reset it in the same update. When the tab changes, drop the params that belong to the old tab. The next demo does both.

Push or replace?

Every update either pushes a new history entry or replaces the current one. The question to ask: should Back undo this?

Change Use Reason
Switching tabs push The user sees it as moving somewhere
Next or previous page push Back should return to the previous page of results
Changing sort or a filter replace (or push) A refinement; many people prefer Back to leave the page
Each keystroke in a search box replace One entry per keystroke would flood the history
Opening a modal push Back should close it
Normalizing a bad URL (?page=abc to the default) replace The bad entry should not stay in history

Neither choice is "wrong"; be consistent inside one app, and test the Back button.

A product page with tabs, sort and pages

The first demo is a product page with a "details" tab and a paged "reviews" tab. Defaults are never written, switching tabs clears the other params, a sort change resets the page and uses replace, and tab and page changes push. The log under the page records which kind of update each click made.

Tabs, sort and pages in the URL

Click "reviews" and the URL becomes /?tab=reviews; switch sort to "rating" and it becomes /?tab=reviews&sort=rating; go to page 2 and &page=2 appears. Click "newest" and the sort key disappears again, while the page resets to 1 because the sort changed. Switching back to "details" returns the URL to just /. Because the app reads everything from the URL, anyone opening /?tab=reviews&sort=rating&page=3 sees exactly that screen.

Typing in a search box should feel instant, but you probably do not want a navigation, a re-filter of a big list, or a network request for every keystroke. The pattern is to keep the text in local state while the user types, and write it to the URL only after a short pause:

sequenceDiagram
  participant U as User
  participant D as Local draft state
  participant T as Timer 400 ms
  participant R as URL with replace
  U->>D: types a letter
  D->>T: restart the timer
  U->>D: types another letter
  D->>T: restart the timer
  T->>R: no typing for 400 ms, write q
  R-->>D: URL changed by us, ignore

Only the pause, not each keystroke, reaches the URL.

There is one subtle trap. The component must also react when the URL changes from elsewhere (the Back button, a "Clear" link), so you copy q from the URL into the draft. If you do that unconditionally, the effect also fires after your own write and can overwrite what the user typed in the meantime. Remember the last value you wrote and ignore the echo:

JSX
const urlQuery = searchParams.get("q") ?? "";
const [draft, setDraft] = useState(urlQuery);
const lastWritten = useRef(urlQuery);

// URL changed from outside (Back, a link): copy it into the input
useEffect(() => {
  if (urlQuery !== lastWritten.current) {
    lastWritten.current = urlQuery;
    setDraft(urlQuery);
  }
}, [urlQuery]);

// User typed: write to the URL after a pause
useEffect(() => {
  if (draft === lastWritten.current) return;
  const timer = setTimeout(() => {
    lastWritten.current = draft;
    setSearchParams((prev) => {
      const next = new URLSearchParams(prev);
      if (draft) next.set("q", draft);
      else next.delete("q");
      return next;
    }, { replace: true });
  }, 400);
  return () => clearTimeout(timer); // typing again cancels the pending write
}, [draft, setSearchParams]);

Debouncing matters most when the URL change triggers expensive work, such as a loader that calls an API. For a small in-memory list, writing the query on every keystroke with replace is simpler and fine, as in the previous lesson.

Modals in the URL

A modal that lives in the URL can be deep-linked (open the page with the dialog already showing), Back closes it, and a refresh keeps it open. The simplest form is a search param naming the item:

JSX
<Link to={`?item=${product.id}`}>View details</Link>

const itemId = searchParams.get("item");
const selected = products.find((p) => String(p.id) === itemId);
{selected && <ProductDialog product={selected} onClose={() => setSearchParams((prev) => { const next = new URLSearchParams(prev); next.delete("item"); return next; })} />}

The second demo combines both patterns: a debounced search over a list, and a details dialog opened with ?item=. Opening pushes an entry, so Back closes the dialog; Escape and the Close button close it too. Type quickly and watch the URL update only after you stop.

Debounced search and a modal in the URL

Type desk and look at the "draft" label: it follows every keystroke, while the URL gets q=desk only after a short pause. Click "Desk lamp" and the dialog opens with ?q=desk&item=1 in the URL (the search is preserved because the new URL copies the existing params). Use the browser's Back button, or press Escape, to close it. Press "Clear" and the input empties as well, because the effect copies the changed URL into the draft.

A modal that appears on top of the page you were on, while the URL points at a different route (for example /photos/12 opening over the gallery), needs one more idea: a "background location". That is the subject of Modal Routes and Background Locations.

Common mistakes

  • Putting everything in the URL. Half-typed inputs, hover states and open dropdowns are not views worth sharing.
  • Storing defaults. Write only the values that differ from the default.
  • Forgetting to reset dependent params. Changing a filter should reset page.
  • Trusting the URL. Whitelist enums, clamp numbers, and fall back to defaults.
  • Pushing on every keystroke. Use replace, a debounce, or both.
  • Sensitive data in the URL. Tokens and personal details belong in cookies or the server, never in a query string.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which piece of state is the best candidate for the URL?

    Tabs, sort and page are small and look the same to everyone, and users expect refresh, Back and shared links to keep them. Half-typed input and tooltips are too transient, and tokens must never appear in URLs.
  2. 2. A user changes the sort order of a list while on page 4. What should the update do?

    Dependent state must change together. A new sort or filter changes what each page contains, so the page number goes back to the default in the same update.
  3. 3. Why are default values (for example tab=details when details is the default) best left out of the URL?

    A missing key already means the default. Omitting it avoids duplicate addresses for the same view and keeps shared links clean.
  4. 4. In the debounced search box, why does the component remember the last value it wrote to the URL?

    When the URL changes, an effect copies it into the draft so Back and links work. Comparing against the last written value tells the component which changes came from outside and which were its own echo.
  5. 5. You open a dialog by changing ?item=3 into the URL. Which history behavior makes Back close the dialog?

    Pushing creates a new entry on top of the list view. Pressing Back removes it, which restores the URL without the item param, and the dialog closes.

Summary

  • Put state in the URL when users expect refresh, Back and shared links to keep it: path for what you see, search params for how you see it.
  • Keep transient or sensitive state out of the URL; use component state, storage or the server.
  • Validate every value against a whitelist or range, and leave defaults out so URLs stay short and unique.
  • Change dependent params together (a new sort resets the page; a new tab clears the old tab's params).
  • Push for steps users think of as navigation (tabs, pages, opening a modal); replace for refinements and typing.
  • Keep typed text in local state, write it to the URL after a pause, and ignore the echo of your own write.

Next: useLocation and Navigation State