React js URL Parameters and Query Parameters Practice Questions with Solutions

Introduction

URL Parameters and Query Parameters are commonly used in React applications to read information from the browser URL. URL parameters are useful for identifying specific resources such as products, users, or blog posts, while query parameters are useful for filtering, searching, sorting, and other optional settings. React Router provides tools such as useParams() and useSearchParams() to work with these values. In this chapter, we will solve practical examples using both. React js URL Parameters and Query parameters practice questions help to understand the concepts.

1. What are URL Parameters in React Router?

URL Parameters are dynamic values included directly in the URL path.

For example:

/products/101

Here, 101 can represent a product ID.

The route can be defined as:

<Route
  path="/products/:productId"
  element={<ProductDetails />}
/>

The :productId part is a URL parameter.

URL parameters are commonly used when the value identifies a specific resource.

Examples:

/users/25
/products/101
/blog/react-hooks
/courses/javascript


2. How do you access URL Parameters using useParams()?

React Router provides the useParams() Hook to access dynamic URL parameters.

Example:

import { useParams } from "react-router-dom";

function ProductDetails() {
  const { productId } = useParams();

  return <h1>Product ID: {productId}</h1>;
}

For this URL:

/products/101

the value of productId will be:

101

The parameter value is provided as a string, so if you need a number for calculations or comparisons, convert it appropriately.


3. What are Query Parameters in React Router?

Query Parameters are optional values added to the URL after a ?.

Example:

/products?category=mobile

Here:

category=mobile

is a query parameter.

Multiple query parameters can be added using &.

/products?category=mobile&sort=price

Query parameters are useful for:

  • Searching
  • Filtering
  • Sorting
  • Pagination
  • Optional settings

Unlike a URL parameter, a query parameter does not normally identify the route itself.


4. How do you read Query Parameters using useSearchParams()?

React Router provides the useSearchParams() Hook for reading and updating query parameters.

Example:

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

function Products() {
  const [searchParams] = useSearchParams();

  const category = searchParams.get("category");

  return <h1>Category: {category}</h1>;
}

For this URL:

/products?category=mobile

the output will be:

Category: mobile

The .get() method reads a query parameter by its name.


5. What is the difference between URL Parameters and Query Parameters?

The main difference is how they are represented and commonly used.

URL Parameter:

/products/101

Route:

<Route
  path="/products/:productId"
  element={<Product />}
/>

Here, 101 identifies a specific product.

Query Parameter:

/products?category=mobile

Here, category=mobile can be used to filter products.

Simple comparison

URL ParametersQuery Parameters
Part of the URL pathAdded after ?
Usually identify a resourceUsually provide optional information
Example /products/101Example /products?category=mobile
Read with useParams()Read with useSearchParams()
Often required for a routeOften optional

6. How do you use Multiple Query Parameters?

You can use multiple query parameters in the same URL.

Example:

/products?category=mobile&sort=price&page=2

You can read them like this:

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

function Products() {
  const [searchParams] = useSearchParams();

  const category = searchParams.get("category");
  const sort = searchParams.get("sort");
  const page = searchParams.get("page");

  return (
    <div>
      <p>Category: {category}</p>
      <p>Sort: {sort}</p>
      <p>Page: {page}</p>
    </div>
  );
}

export default Products;

Output:

Category: mobile
Sort: price
Page: 2

Multiple query parameters are useful for building search and filter pages.


7. How do you update Query Parameters using useSearchParams()?

useSearchParams() returns a setter function that can update the query string.

Example:

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

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

  function showMobiles() {
    setSearchParams({
      category: "mobile"
    });
  }

  return (
    <div>
      <button onClick={showMobiles}>
        Show Mobiles
      </button>

      <p>Category: {searchParams.get("category")}</p>
    </div>
  );
}

export default Products;

When the button is clicked, the URL can become:

/products?category=mobile

This makes the filter state visible in the URL.


8. How do you use URL Parameters and Query Parameters together?

You can use both types of parameters in the same application.

For example:

/products/101?color=black&size=large

Here:

101

is a URL parameter.

And:

color=black
size=large

are query parameters.

The route can be:

<Route
  path="/products/:productId"
  element={<ProductDetails />}
/>

The component can read both:

import {
  useParams,
  useSearchParams
} from "react-router-dom";

function ProductDetails() {
  const { productId } = useParams();
  const [searchParams] = useSearchParams();

  const color = searchParams.get("color");
  const size = searchParams.get("size");

  return (
    <div>
      <h1>Product ID: {productId}</h1>
      <p>Color: {color}</p>
      <p>Size: {size}</p>
    </div>
  );
}

export default ProductDetails;

For:

/products/101?color=black&amp;size=large

the component receives:

Product ID: 101
Color: black
Size: large


9. How do you create a Product Search using Query Parameters?

Query parameters are useful for creating search functionality.

Example:

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

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

  const search = searchParams.get("search") || "";

  function handleChange(event) {
    setSearchParams({
      search: event.target.value
    });
  }

  return (
    <div>
      <input
        type="text"
        value={search}
        onChange={handleChange}
        placeholder="Search products"
      />

      <p>Searching for: {search}</p>
    </div>
  );
}

export default ProductSearch;

If the user enters:

Laptop

the URL can become:

/products?search=Laptop

This is useful because the search value is stored in the URL and can be shared or revisited.


10. How do you Build a Practical Product Filter using URL and Query Parameters?

Let’s create a practical example where the product ID comes from the URL and the category comes from a query parameter.

import {
  BrowserRouter,
  Routes,
  Route,
  Link,
  useParams,
  useSearchParams
} from "react-router-dom";

const products = [
  {
    id: "1",
    name: "Laptop",
    category: "electronics",
    price: 55000
  },
  {
    id: "2",
    name: "Mobile",
    category: "electronics",
    price: 30000
  },
  {
    id: "3",
    name: "Shoes",
    category: "fashion",
    price: 2500
  }
];

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          path="/products"
          element={<Products />}
        />

        <Route
          path="/products/:productId"
          element={<ProductDetails />}
        />
      </Routes>
    </BrowserRouter>
  );
}

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

  const category = searchParams.get("category") || "";

  const filteredProducts = category
    ? products.filter(
        (product) => product.category === category
      )
    : products;

  function handleCategoryChange(event) {
    const value = event.target.value;

    if (value) {
      setSearchParams({
        category: value
      });
    } else {
      setSearchParams({});
    }
  }

  return (
    <div>
      <h1>Products</h1>

      <select
        value={category}
        onChange={handleCategoryChange}
      >
        <option value="">All Products</option>
        <option value="electronics">Electronics</option>
        <option value="fashion">Fashion</option>
      </select>

      {filteredProducts.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>₹{product.price}</p>

          <Link to={`/products/${product.id}`}>
            View Details
          </Link>
        </div>
      ))}
    </div>
  );
}

function ProductDetails() {
  const { productId } = useParams();

  const product = products.find(
    (item) => item.id === productId
  );

  if (!product) {
    return <h2>Product Not Found</h2>;
  }

  return (
    <div>
      <h1>{product.name}</h1>
      <p>Product ID: {product.id}</p>
      <p>Category: {product.category}</p>
      <p>Price: ₹{product.price}</p>

      <Link to="/products">
        Back to Products
      </Link>
    </div>
  );
}

export default App;

How this application works

The product list uses a query parameter:

/products?category=electronics

The selected category is read using:

const category = searchParams.get("category");

The product details page uses a URL parameter:

/products/1

The product ID is read using:

const { productId } = useParams();

Therefore, the application uses:

URL Parameter → Identify a specific product

Query Parameter → Filter the product list

This pattern is commonly used in real-world React applications for product catalogs, search pages, dashboards, blogs, and other data-driven interfaces.

Key Takeaways

  • URL Parameters are dynamic values included in the route path.
  • Query Parameters are values added after ? in the URL.
  • useParams() is used to read URL parameters.
  • useSearchParams() is used to read and update query parameters.
  • URL parameters are commonly used to identify specific resources.
  • Query parameters are useful for search, filtering, sorting, and pagination.
  • Multiple query parameters can be combined using &.
  • URL and query parameters can be used together.
  • Query parameters can make search and filter state shareable through the URL.
  • Always handle missing or invalid parameter values appropriately.

FAQs

1. What are URL Parameters in React Router?

URL Parameters are dynamic values included in a route path, such as /products/101, where 101 identifies a specific product.

2. What are Query Parameters in React?

Query Parameters are optional values added to the URL after ?.

Example:

/products?category=mobile

3. Which Hook is used to read URL Parameters?

React Router provides the useParams() Hook.

const { productId } = useParams();

4. Which Hook is used for Query Parameters?

The useSearchParams() Hook is commonly used to read and update query parameters.

const [searchParams, setSearchParams] = useSearchParams();

5. Can a URL have both URL Parameters and Query Parameters?

Yes.

Example:

/products/101?color=black

Here:

101 → URL Parameter
color=black → Query Parameter

6. Can Query Parameters be used for search and filtering?

Yes. Query parameters are commonly used for search, filtering, sorting, pagination, and other optional URL state.

Example:

/products?search=laptop&sort=price

7. What is the difference between useParams() and useSearchParams()?

useParams() reads dynamic values from the route path.

/products/101

useSearchParams() reads values from the query string.

/products?category=mobile

So, useParams() is mainly for route parameters, while useSearchParams() is useful for query parameters.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top