liveBook · Manning

useSearchParams

As explained in React Hooks in Action: With Suspense and Concurrent Mode

useSearchParams is a React Router hook that provides the current URL search parameters and a function for updating them.

useSearchParams is a React Router hook for keeping application state in a URL query string. It returns a searchParams object for reading values and a setter for updating them, so users can link directly to a selected bookable and date. section 10.2 section 10.2.1

Use the hook in a component or wrap it in a domain-specific custom hook:

  • Read values with searchParams.get("date") and searchParams.get("bookableId"). section 10.2.1
  • Validate values before using them; the bookings example accepts valid dates and integer bookable IDs, treating invalid values as missing. section 10.2.1
  • Update the query string by passing an object to setSearchParams; consumers re-render with the new URL state. section 10.2.2
  • Pass {replace: true} when repeated controls such as a week picker should replace the current browser-history entry. section 10.2.2

Bookings page state

A URL such as /bookings?bookableId=1&date=2020-06-24 identifies both selections. A custom hook can expose sanitized values and a date updater: const [searchParams, setSearchParams] = useSearchParams(); const date = searchParams.get("date"); const bookableId = searchParams.get("bookableId"); setSearchParams({bookableId: 1, date: "2020-06-24"}, {replace: true}); section 10.2 section 10.2.2

  const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("date");
  searchParams.get("bookableId");

View the compact API pattern for obtaining the hook tuple and reading both query parameters. section 10.4

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains tuple access, parameter validation, setter objects, and history replacement, but does not descend into React Router internals.
Examples
Uses a bookings page, bookable IDs, dates, a week picker, and URLs such as /bookings?bookableId=1&date=2020-06-24.
What it assumes
Assumes React function components and basic React Router routing while demonstrating custom-hook extraction for URL-state handling.
What you can do after
Apply it via React Router to read, validate, and update URL-backed component state.
How it connects
Connects React Router, URL query strings, custom hooks, useNavigate, component state, and re-rendering.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.