Course contentsShow
← React
Lesson 1862 of 2,39643. RoutingFree lesson

Preserving Search Params During Navigation

Combine useSearchParams with navigate to maintain filters or pagination across route changes.

Preserving Search Params During Navigation

What you'll learn: How to maintain query parameters like filters or pagination when navigating between routes.

When users navigate from one route to another, they often expect their current filters, sort options, or pagination settings to persist. Without explicit handling, useNavigate drops all search params by default—your carefully filtered product list becomes unfiltered after clicking through to a detail page and back.

The solution combines useSearchParams with navigate to read current params and preserve them during navigation.

Why This Matters

Imagine a user filtering products by category and price range. If they click a product detail link, then hit "Back," losing those filters creates a frustrating experience. Preserving search params maintains application state across routes.

The Pattern

import { useNavigate, useSearchParams } from 'react-router-dom';

function ProductList() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  const handleViewDetails = (productId) => {
    // Get current params as object
    const currentParams = Object.fromEntries(searchParams);
    
    // Navigate with preserved params
    navigate(`/products/${productId}?${searchParams.toString()}`);
    
    // Or construct new URLSearchParams
    const params = new URLSearchParams(currentParams);
    navigate(`/products/${productId}?${params}`);
  };
}

You can also preserve params when going back:

const handleBackToList = () => {
  navigate(`/products?${searchParams.toString()}`);
};

Selective Preservation

Sometimes you want to preserve some params but not others:

const currentParams = Object.fromEntries(searchParams);
delete currentParams.page; // Reset pagination, keep filters
navigate(`/products?${new URLSearchParams(currentParams)}`);

Key Takeaway: Use searchParams.toString() or Object.fromEntries(searchParams) to capture current query parameters and append them to your navigation target, ensuring users don't lose their filters, sorts, or pagination state across route changes.