Redirecting Based on Search Params
You'll learn how to automatically redirect users when certain query string conditions are met, combining useSearchParams with useNavigate in effects.
Sometimes you need to enforce navigation rules based on what's in the URL's query string. For example, if a user lands on /products?view=grid but you've deprecated the grid view, you might want to automatically redirect them to /products?view=list. Or if a search query is invalid, redirect to a default state.
The Pattern: Read, Check, Redirect
You combine useSearchParams (to read the query string) with useNavigate (to redirect) inside a useEffect:
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
function ProductList() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
useEffect(() => {
const view = searchParams.get('view');
// Redirect deprecated "grid" view to "list"
if (view === 'grid') {
navigate('/products?view=list', { replace: true });
}
// Redirect missing view param to default
if (!view) {
navigate('/products?view=list', { replace: true });
}
}, [searchParams, navigate]);
return <div>Product list content...</div>;
}
Why replace: true?
Use replace: true so the invalid URL doesn't pollute the browser history—users won't get stuck in a redirect loop when hitting "back."
Think of it like a bouncer at a club: If someone shows up with the wrong ticket (invalid search param), the bouncer immediately redirects them to the correct entrance without adding a "wrong entrance" entry to their path history.
Key Takeaway: Combine useSearchParams and useNavigate in a useEffect to enforce query string rules by redirecting users when conditions aren't met—use replace: true to avoid history pollution.