Thuta Learning
React
AdvancedWeb DevelopmentIntermediate

URL Parameters

ReactLesson 2035 min

What you'll walk away with

  • Write a route with a dynamic segment such as :userId and read its value with useParams
  • Convert and validate URL parameters, which are always strings or undefined
  • Keep optional state such as filters, sorting and paging in the URL with useSearchParams
  • Change screens from code with useNavigate, for example after a form submit

Explain it simply

URL parameters in plain language

An online shop with a thousand products does not write a thousand routes. It writes one pattern, /products/:productId, and the component reads the changing part of the URL, the 15 in /products/15, as a parameter. In /users/sai, sai could be a username.

The part of a URL after the ?, such as ?sort=price&page=2, carries information too; these are search parameters, also called the query string. A path parameter usually says which item, while search parameters say how to show things: sorting, filtering and paging.

Problem → Why → Solution

The problem: a mismatched parameter name loses the value

The route says /users/:userId, but the component reads const { id } = useParams(). Nothing throws, yet the screen shows 'User Profile ID:' with no number. One step later, fetch(`/api/users/${id}`) requests /api/users/undefined and the server answers 404.

UserProfile.jsx
<Route path="/users/:userId" element={<UserProfile />} />

function UserProfile() {
  const { id } = useParams(); // undefined: the segment is called userId
  return <h2>User Profile ID: {id}</h2>;
}

Why there is no error

useParams() returns a plain JavaScript object whose keys are exactly the names after the colons in the route pattern. Destructuring a key that does not exist gives undefined, not an error. So the name in the route and the name in the component must match letter for letter, and the component must also handle a missing value.

Core concept: every part of the URL is readable input

A segment that starts with a colon in a route path is a dynamic segment. /users/:userId matches any two-segment URL such as /users/123 or /users/abc and captures the second segment under the name userId. One route can hold several parameters, as in /teams/:teamId/members/:memberId, and useParams() returns them all in one object such as { teamId, memberId }.

Parameter values are always strings, because a URL is just text. In /users/123, userId is the string "123", not the number 123, so a comparison such as p.id === userId never succeeds when id is a number. Convert with Number(userId) and check with Number.isNaN, and always prepare a 'not found' screen, because anyone can type /users/abc by hand.

Two special patterns exist too. A ? after a segment makes it optional: /:lang?/about matches both /about (lang is undefined) and /my/about (lang is "my"). A * (splat) at the end of a path captures the whole remaining path and puts it in params['*'], which is useful for paths that contain slashes, such as a file browser.

URL partHow to read itFor /shop/7?sort=price
Dynamic segment (:id)useParams(){ id: "7" }
Search parameteruseSearchParams()searchParams.get('sort') -> "price"
Splat (*)useParams()['*']the rest of the path, e.g. a/b.txt under /files/*

One detail needs care: moving from /users/1 to /users/2 keeps the same route and the same component, with only the params changing; the component is not unmounted and mounted again. Local useState values, such as a form draft, can therefore keep the previous user's data, and an effect that runs only on mount will not fetch the new user. List userId as an effect dependency, and when state must start fresh, give the component a key, as in <UserProfile key={userId} />.

The URL is input to the component
  1. The pattern captures :name segments
  2. useParams() returns string values
  3. The component converts and validates
  4. New params: re-render, not remount

Treat the URL like a form field the user can type anything into: never trust it blindly.

General pattern

jsx
<Route path="/items/:itemId" element={<ItemPage />} />

function ItemPage() {
  const { itemId } = useParams();               // string | undefined
  const [searchParams, setSearchParams] = useSearchParams();
  const view = searchParams.get('view') ?? 'default';
  const navigate = useNavigate();
  // setSearchParams({ view: 'compact' });  navigate('/somewhere');
}

Read path values with useParams, values after the ? with useSearchParams, and use useNavigate to move from code. All three come from react-router and work only in components under the router.

Worked example: a user list and a profile page

/users shows a list of users, and each link goes to a dynamic URL such as /users/123. A single route handles every profile, and UserProfile reads the id from the URL and shows it.

App.jsx
import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router';

function UserList() {
  return (
    <ul>
      <li><Link to="/users/123">User 123</Link></li>
      <li><Link to="/users/456">User 456</Link></li>
    </ul>
  );
}

function UserProfile() {
  const { userId } = useParams(); // always a string, e.g. "123"
  return <h2>User Profile ID: {userId}</h2>;
}

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/users" element={<UserList />} />
        <Route path="/users/:userId" element={<UserProfile />} />
      </Routes>
    </BrowserRouter>
  );
}

Code breakdown

  1. Links build the dynamic URL<li><Link to="/users/123">User 123</Link></li>

    Each Link points to a URL with a different id. With real data you would build it with a template literal such as to={`/users/${user.id}`}.

  2. One route for every profile<Route path="/users/:userId" element={<UserProfile />} />

    :userId captures the segment after /users/. It does not clash with the /users route, because /users has only one segment and does not match this pattern.

  3. Read the parameterconst { userId } = useParams(); // always a string, e.g. "123"

    The destructured name must match :userId in the route exactly. The value is a string, so convert it if you need a number.

  4. Render from the URLreturn <h2>User Profile ID: {userId}</h2>;

    The component simply shows the value taken from the URL. Moving from one profile link to another re-renders the same component, and the heading shows the new id.

You should see
At /users it shows a list with two links, 'User 123' and 'User 456'. Clicking 'User 123' changes the URL to /users/123 and shows 'User Profile ID: 123'.

Search parameters: sort, filter and page in the URL

Keeping 'sorted by price' in useState means it vanishes on refresh, and anyone opening a shared link sees the default order. useSearchParams keeps that setting in the URL instead. The hook returns [searchParams, setSearchParams]; searchParams is the browser's URLSearchParams object, so you read with get('sort'), which returns null when the parameter is absent.

SortControls.jsx
function SortControls() {
  const [searchParams, setSearchParams] = useSearchParams();
  const sort = searchParams.get('sort') ?? 'name'; // null when absent

  return (
    <>
      <p>Sorted by {sort}</p>
      <button onClick={() => setSearchParams({ sort: 'price' })}>By price</button>
    </>
  );
}

setSearchParams({ sort: 'price' }) navigates to ?sort=price and re-renders the component. Passing an object replaces the whole query string, so other parameters such as page=3 can disappear; to keep them, copy the current searchParams and call set on the copy.

useNavigate: navigating from code

Sometimes the screen should change after an action rather than a link click, such as sending the user to the order page after a successful order form submit. const navigate = useNavigate() gives you a function, and navigate('/orders/42') works like clicking a Link. navigate(-1) goes one step back in history like the Back button, and navigate('/login', { replace: true }) replaces the current history entry, so Back does not return to that screen. For ordinary links the user clicks, keep using Link, which is better for Ctrl-click and accessibility.

In real projects

URL parameters in real projects

In well-built web apps the answer to 'can I share this screen as a link?' is usually yes. That works because the information that defines the screen lives in the URL.

  • Detail pages: routes such as /products/:productId, /orders/:orderId and /posts/:slug read the id or slug and fetch data from an API, with the parameter listed as an effect dependency.
  • Search and filter pages: a URL such as /search?q=react&category=books&page=2 gives the same results after a refresh, and Back returns to the previous filters.
  • Multi-language sites: an optional segment such as /:lang?/about lets one route handle both /about and /my/about.
  • Finishing forms: after a successful checkout, navigate(`/orders/${id}`, { replace: true }) means Back does not return to the payment form.

Common mistakes

Common mistakes with URL parameters

Mismatched parameter names

Writing :userId in the route and { id } in the component gives undefined with no error, as in the problem section. Whenever you rename a route parameter, search for the components that read it. TypeScript projects can use type-safe routing options that catch this early.

Comparing a string with a number

products.find((p) => p.id === productId) compares the number 2 with the string "2" using ===, never finds anything and always shows 'product not found'. Convert with Number(productId) before comparing, and show a not-found UI for invalid input.

Assuming a new param remounts the component

Moving from /notes/1 to /notes/2 leaves note 1's draft in the edit box, because a useState initial value is used only on the first mount. A fetch inside useEffect(..., []) also never loads note 2. Add noteId to the dependencies, or reset the component with key={noteId}.

Mini challenge

Mini challenge: a sortable product catalog

At /products, show the product list sorted by price when ?sort=price is present and by name otherwise. Each product links to /products/:productId; the detail page converts the id to a number, looks the product up, and has a 'Back to list' button that returns to the list.

  • Keep the sort mode in the URL with useSearchParams, not in state
  • Two buttons, 'Sort by price' and 'Sort by name', call setSearchParams
  • ProductPage looks up Number(productId) and shows 'No product with id "..."' when nothing matches
  • A 'Back to list' button goes to /products with useNavigate
Catalog.jsx
import {
  BrowserRouter, Routes, Route, Link, useParams, useSearchParams, useNavigate,
} from 'react-router';

const products = [
  { id: 1, name: 'Keyboard', price: 49 },
  { id: 2, name: 'Mouse', price: 19 },
  { id: 3, name: 'Monitor', price: 189 },
];

function ProductList() {
  // TODO: read "sort" from the search params ('price' or default 'name')
  // TODO: sort a copy of products, render two sort buttons and a list of Links
  return null;
}

function ProductPage() {
  // TODO: read productId, convert it, find the product (or show "No product...")
  // TODO: show name and price, plus a "Back to list" button using navigate
  return null;
}

export default function App() {
  // TODO: routes for /products and /products/:productId inside a BrowserRouter
  return null;
}

Expected: /products lists Keyboard, Monitor, Mouse (by name). 'Sort by price' changes the URL to /products?sort=price and the order to Mouse (19), Keyboard (49), Monitor (189), which survives a refresh. Clicking Mouse shows 'Mouse' and 'Price: 19 USD' at /products/2, and /products/abc shows 'No product with id "abc".'.

Show hint

Writing searchParams.get('sort') === 'price' ? 'price' : 'name' also sends unexpected values to the default. Copy with [...products] before sorting, because .sort() mutates the original array. setSearchParams({}) clears the query string.

Show solution
Catalog.jsx
import {
  BrowserRouter, Routes, Route, Link, useParams, useSearchParams, useNavigate,
} from 'react-router';

const products = [
  { id: 1, name: 'Keyboard', price: 49 },
  { id: 2, name: 'Mouse', price: 19 },
  { id: 3, name: 'Monitor', price: 189 },
];

function ProductList() {
  const [searchParams, setSearchParams] = useSearchParams();
  const sort = searchParams.get('sort') === 'price' ? 'price' : 'name';
  const sorted = [...products].sort((a, b) =>
    sort === 'price' ? a.price - b.price : a.name.localeCompare(b.name)
  );

  return (
    <>
      <button onClick={() => setSearchParams({ sort: 'price' })}>Sort by price</button>
      <button onClick={() => setSearchParams({})}>Sort by name</button>
      <ul>
        {sorted.map((p) => (
          <li key={p.id}>
            <Link to={`/products/${p.id}`}>{p.name}</Link> ({p.price} USD)
          </li>
        ))}
      </ul>
    </>
  );
}

function ProductPage() {
  const { productId } = useParams();
  const navigate = useNavigate();
  const product = products.find((p) => p.id === Number(productId));

  if (!product) return <p>No product with id "{productId}".</p>;

  return (
    <>
      <h1>{product.name}</h1>
      <p>Price: {product.price} USD</p>
      <button onClick={() => navigate('/products')}>Back to list</button>
    </>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/products" element={<ProductList />} />
        <Route path="/products/:productId" element={<ProductPage />} />
      </Routes>
    </BrowserRouter>
  );
}

Quick quiz 1 / 3

The route is path="/orders/:orderId" and the user opens /orders/42. What does useParams() return?

Quick quiz 2 / 3

A product list's sort order should survive a refresh and travel with a shared link. Where should it live?

Quick quiz 3 / 3

NoteEditor starts with const [draft, setDraft] = useState(note.text). After a Link from /notes/1 to /notes/2, the edit box still holds note 1's text. What is the best fix?

What to remember

  • :name segments capture parts of the URL, and useParams() returns an object keyed by those names
  • Parameters are always strings (or undefined): convert, validate and prepare a not-found UI
  • Keep optional settings such as sorting, filtering and paging in the URL with useSearchParams
  • Use useNavigate to change screens after an action, and keep Link for links the user clicks
  • New params do not remount the component, so handle them with effect dependencies or a key

React Router Documentation — React Router

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

URL Parameters | Thuta Learning