#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Routing and Navigation

Working with Query Param

Query parameters are the key-value pairs after the ? in a URL, like /products?category=books&sort=price. In React Router you read and update them with the useSearchParams hook. You use them for state that should survive a page refresh and be shareable as a link: search terms, filters, sort order and the current page number.

Route params versus query params

Route parameterQuery parameter
Example URL/products/42/products?sort=price
Declared in the route?Yes, as :productIdNo, any route can receive them
Typical useIdentifies which resourceOptions that change how it is shown
Read withuseParams()useSearchParams()
Optional?Required for the route to matchAlways optional

Reading and updating with useSearchParams

useSearchParams returns a pair, similar to useState: a URLSearchParams object for reading, and a setter that updates the URL. Changing the URL causes a re-render with the new values.

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

function ProductList({ products }) {
  const [searchParams, setSearchParams] = useSearchParams();

  const sort = searchParams.get('sort') ?? 'name';
  const page = Number(searchParams.get('page') ?? '1');

  const sorted = [...products].sort((a, b) =>
    sort === 'price' ? a.price - b.price : a.name.localeCompare(b.name)
  );

  function changeSort(value) {
    setSearchParams((prev) => {
      const next = new URLSearchParams(prev);
      next.set('sort', value);
      next.set('page', '1');
      return next;
    });
  }

  return (
    <>
      <button onClick={() => changeSort('name')}>By name</button>
      <button onClick={() => changeSort('price')}>By price</button>
      <p>Page {page}</p>
      <ul>{sorted.map((p) => <li key={p.id}>{p.name}</li>)}</ul>
    </>
  );
}

get() returns null when a key is missing, which is why the code uses ?? to supply defaults. Other handy methods on the same object are has(key) to check presence, getAll(key) for repeated keys such as ?tag=js&tag=css, and delete(key) to remove one.

Why keep this state in the URL

You could store the sort order in useState instead. The difference shows up the moment someone refreshes the page or copies the link to a friend: component state resets to its default, while the URL keeps the exact view. Back and Forward buttons also work naturally, because each view has its own address. Keep short-lived UI details, like whether a dropdown is open, in component state, and put anything a user might want to bookmark or share in the query string.

Values are always strings

Everything in a query string is text. searchParams.get('page') returns "2", not 2. Doing arithmetic like page + 1 on the raw value gives "21". Convert numbers with Number() and booleans with a comparison like get('inStock') === 'true', and guard against nonsense values that users might type into the address bar.

The pitfall of replacing every parameter

Calling setSearchParams({ sort: 'price' }) replaces the whole query string. Any other parameter, such as category=books, is silently dropped, and the user loses their filter. To change one value and keep the rest, pass a function that copies the previous params, as the example does, and set only the key you mean to change.

Also think about history. Each update adds a browser history entry by default, so pressing Back steps through every sort click. For rapid changes like typing in a search box, pass { replace: true } as the second argument to update the current entry instead.

Building links with query strings

You can also put query parameters straight into links: <Link to="/products?sort=price">. When values come from user input, build the string with new URLSearchParams({ q: term }).toString() so spaces and special characters are encoded correctly.

In short: use route params to pick a resource, query params for options, convert strings before using them, and update one key at a time without dropping the others.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course