Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 15 / Topic 5 of 9

useSearchParams and useNavigate

useSearchParams holds the ?... part of the URL as a real URLSearchParams, read and replaced the same immutable way Part 3 already taught state - not mutated in place. examples/05_usenavigate_and_search_params.jsx's cuisine filter keeps its current choice in the URL instead of a local useState:

// examples/05_usenavigate_and_search_params.jsx
const [searchParams, setSearchParams] = useSearchParams();
const cuisine = searchParams.get("cuisine") ?? "all";

function filterBy(nextCuisine) {
  setSearchParams(nextCuisine === "all" ? {} : { cuisine: nextCuisine });
}

Landing straight on /search?cuisine=north-indian really shows only "Punjabi Tadka," pre-filtered, with no click needed at all (examples/05_usenavigate_and_search_params.test.jsx) - the exact thing a useState("all") version could never do, since a plain refresh would reset it back to the default. This is the difference that matters: URL state is shareable and survives a reload; component state is neither.

useNavigate is for moving the user when nobody is clicking a link - PlaceOrderButton calls it after an action finishes, not as a stand-in for a normal click:

// examples/05_usenavigate_and_search_params.jsx
const navigate = useNavigate();
function handleClick() {
  navigate(`/orders/${restaurantId}/confirmation`);
}

Clicking "Place order" really lands on the confirmation route for that same restaurant id (examples/05_usenavigate_and_search_params.test.jsx). The installed package's own navigating doc is explicit about when not to reach for this: ordinary navigation should stay a <Link>/<NavLink>, which gets keyboard handling, right-click-to-open-in-new-tab, and accessibility labeling for free - useNavigate is for "after a form submission completes," "logging someone out after inactivity," timed flows - moments with no click to attach a <Link> to.

Done here? The practice set for Part 15 — including the solutions — is on the part page.

Search the guide