Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Working with Query Parameters | Advanced React Router Features
React Router Essentials

book
Working with Query Parameters

The useSearchParams is a hook that provides access to the query parameters (search parameters) of the current URL. Query parameters are key-value pairs that follow the question mark (?) in a URL. For example, in the URL http://example.com/products?category=electronics&page=2, the query parameters are category=electronics and page=2.

What Does useSearchParams Return?

The useSearchParams hook returns an array with two elements: an object representing the current query parameters and a function to update the query parameters. Here's how you can use the hook:

js
import { useSearchParams } from "react-router-dom";

function MyComponent() {
const [searchParams, setSearchParams] = useSearchParams();

// `searchParams` is an object representing the current query parameters
// `setSearchParams` is a function to update the query parameters
}

The searchParams Object

The searchParams object is an instance of the URLSearchParams class. It provides convenient methods to interact with query parameters, such as:

  • get(key): Retrieves the value associated with a specific key;
  • getAll(key): Retrieves all values associated with a specific key;
  • set(key, value): Sets or updates the value of a specific key;
  • append(key, value): Appends a new value to an existing key;
  • delete(key): Deletes a specific key and its associated value;
  • toString(): Returns the query parameters as a string (e.g., "?category=electronics&page=2").

The setSearchParams Function

The setSearchParams function allows you to update the query parameters in the URL. You can pass it an object with key-value pairs to set new parameters or modify existing ones. Here's an example of how to use it:

js
// Suppose the current URL is `http://example.com/products?category=electronics&page=2`

setSearchParams({ category: "clothing", color: "blue" });

// The URL is now `http://example.com/products?category=clothing&color=blue`

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 5
some-alt