Back to all posts
·8 min read

Keeping state in the URL in React: search params for filters, sorting and pagination

Imagine picking a category in a product list, sorting by price and moving to page three. You click a product, then go back, and the list greets you reset to the first page with the default sort order. When you want to send the same view to a colleague, there is no shareable link either; you have to describe which filters they should pick.

The common cause of these problems is that the information describing "where the user is" lives in component state (useState). When the component unmounts, that information is gone. Yet the browser offers a place built exactly for this: the URL. In this post I describe how to keep information such as filters, sorting and pagination in search params, how to make that typed and predictable, and the traps you tend to run into.

Which state belongs in the URL?

Moving every piece of state into the URL is not the right call. The simple question I use is: "Should someone who opens this page in a new tab see the same thing?" If the answer is yes, the state most likely belongs in the URL.

  • Fits the URL: search text, filters, sort order, page number, the selected tab, the ID of the record that is open.
  • Stays in the component: whether a dropdown is open, the row under the mouse, form fields that have not been submitted yet, transient loading flags.
  • Belongs to the server: the list itself. The URL does not describe the data, it describes how to ask for it.

This distinction matters because the URL is a public interface. Users copy it, bookmark it and edit it by hand. Every parameter you put into the URL is therefore a small contract, and it should never contain sensitive information.

Reading and writing parameters with types

URLSearchParams returns every value as a string and guarantees nothing. Values like ?page=abc, ?page=-3 or ?sort=unknown will show up sooner or later. So instead of reading the URL directly in components, I write a small layer that parses it in one place and turns invalid values into defaults:

type SortKey = "newest" | "price-asc" | "price-desc";

export type ProductFilters = {
  q: string;
  category: string | null;
  sort: SortKey;
  page: number;
};

const SORT_KEYS: SortKey[] = ["newest", "price-asc", "price-desc"];
const DEFAULTS: ProductFilters = { q: "", category: null, sort: "newest", page: 1 };

export function parseFilters(params: URLSearchParams): ProductFilters {
  const sort = params.get("sort");
  const page = Number(params.get("page"));
  return {
    q: params.get("q")?.trim() ?? "",
    category: params.get("category") || null,
    sort: SORT_KEYS.includes(sort as SortKey) ? (sort as SortKey) : DEFAULTS.sort,
    page: Number.isInteger(page) && page > 0 ? page : DEFAULTS.page,
  };
}

export function serializeFilters(f: ProductFilters): URLSearchParams {
  const params = new URLSearchParams();
  if (f.q) params.set("q", f.q);
  if (f.category) params.set("category", f.category);
  if (f.sort !== DEFAULTS.sort) params.set("sort", f.sort);
  if (f.page !== DEFAULTS.page) params.set("page", String(f.page));
  return params;
}

The two functions are inverses of each other, which makes them easy to verify with plain unit tests. serializeFilters does not write default values into the URL; that way the unfiltered page has a clean address and the same view does not end up with several different URLs. Falling back to the default instead of throwing on an invalid value is also a deliberate choice: a hand-edited or outdated link should not show the user an error screen.

Giving components a small hook

So that components never have to deal with URLSearchParams, I hide these two functions behind a hook. The example below uses React Router's useSearchParams hook; if you use a different router, the idea stays the same:

export function useProductFilters() {
  const [params, setParams] = useSearchParams();
  const filters = useMemo(() => parseFilters(params), [params]);

  const update = useCallback(
    (patch: Partial<ProductFilters>, options?: { replace?: boolean }) => {
      const next = { ...filters, ...patch };
      if (!("page" in patch)) next.page = 1;
      setParams(serializeFilters(next), options);
    },
    [filters, setParams],
  );

  return { filters, update };
}

The small but important rule here: whenever any filter other than the page changes, the page number goes back to one. Forgetting this drops the user onto an empty page seven after they pick a new category. Keeping the rule in one place means no component has to remember it on its own.

Push or replace?

There are two ways to update the URL: adding a new entry to the history (push) or replacing the current one (replace). This choice determines how the back button behaves and has a direct effect on the user experience.

The criterion I use: is this a step the user would want to "go back" to? Changing the page or choosing a category usually is; the back button should return to the previous page or category. On the other hand, every letter typed into a search box, the intermediate values of a slider or a parameter that gets corrected automatically should not fill up the history. For those I use replace. Otherwise the user has to press back fifteen times just to leave the list.

The search box: local state, delayed URL

The search box is the most delicate part of this setup. Updating the URL on every keystroke produces unnecessary requests and, in some cases, makes the cursor jump. The solution is to let the input keep its own local state and update the URL after a short delay:

function SearchBox() {
  const { filters, update } = useProductFilters();
  const [text, setText] = useState(filters.q);

  // If the URL changes from outside (back button, link), sync the field.
  useEffect(() => {
    setText((prev) => (prev.trim() === filters.q ? prev : filters.q));
  }, [filters.q]);

  useEffect(() => {
    const value = text.trim();
    if (value === filters.q) return;
    const id = setTimeout(() => update({ q: value }, { replace: true }), 300);
    return () => clearTimeout(id);
  }, [text, filters.q, update]);

  return (
    <input
      type="search"
      value={text}
      onChange={(e) => setText(e.target.value)}
      aria-label="Search products"
    />
  );
}

The URL remains the single source of truth here, while the input holds a short-lived draft. The first effect makes sure the field lines up with the URL when the user presses back. Comparing against the trimmed text prevents a space from being removed while the user is typing it between words.

Deriving data from the URL

Once the URL carries the state, fetching data gets simpler. The parsed filter object becomes the query key directly, and when the URL changes the right data is requested on its own. With TanStack Query it looks like this:

function ProductList() {
  const { filters } = useProductFilters();
  const { data, isPending, isPlaceholderData } = useQuery({
    queryKey: ["products", filters],
    queryFn: ({ signal }) => fetchProducts(serializeFilters(filters), signal),
    placeholderData: keepPreviousData,
  });
  // ...
}

This approach has several benefits. When the back button restores earlier filters and that query is in the cache, the result appears immediately. Thanks to signal, the old request is cancelled when the user changes filters quickly. keepPreviousData keeps the list from suddenly going blank while the new page loads; with isPlaceholderData you can dim the list slightly to signal loading. Using the same serializeFilters function for the API request also stops parameter names from drifting apart between client and server.

Edge cases and small rules

After using this setup in several projects, these are the points I have noted:

  • Keep parameter names short and stable. URLs get shared and bookmarked. If you rename a parameter, old links quietly stop working. If you have to, read the old name in the parser as well and map it to the new one.
  • Correct the page when it goes out of range. If page twenty no longer exists because there are fewer results, redirect to the last valid page with replace. Showing an empty list gives the user the impression that something is broken.
  • Store multiple values consistently. For several categories, pick either ?category=a&category=b or ?category=a,b and use it everywhere. Sorting the values ensures a single URL for the same selection.
  • Do not put large objects in the URL. A complex query builder or a long selection list makes the URL unreadable and can run into length limits. In such cases it is better to store the state on the server and write only an ID into the URL.
  • Use the same defaults on the server. When a parameter is missing, the API should apply the same sort order and page size the client assumes. Otherwise the same URL can produce different results.

Conclusion

Keeping filters, sorting and pagination in the URL is not a big architectural decision, but a back button that works as expected, a page that reopens with the same view after a refresh and a link that can be shared make a real difference for users. What matters is treating the URL not as text read here and there but as a typed contract: parse it in one place, keep defaults out of the URL, decide deliberately when to add a history entry, and derive the data from that contract. Once these rules are in place, every new filter added to a list screen fits into the same structure without trouble.