日本語

How to Get URL Values with useParams in React Router

​​React​React Router,TypeScript,Vite

In React Router, if you write a segment that starts with : in a route's path, such as /cats/:catId, you can read its value in the component with useParams(). This is useful when one component should show different content for each ID, such as a product or article detail page.

In my test environment, I checked what useParams() returns for a route with one parameter, several parameters, an optional parameter, and *. I also checked the type of the values, how they appear in parent and child routes, and whether state is kept when navigation changes only the ID.

Note

The test environment was Ubuntu 24.04 with Node.js 22.23.4. I created a project with the react-ts template from npm create vite@latest (React 19.3.1, Vite 8.3.8, TypeScript 7.0.2), added React Router 8.5.1, and tested in declarative mode using <BrowserRouter> and <Routes>, with the components wrapped in StrictMode. I opened the pages in Chromium 153 operated with Playwright 1.63.0. I did not test the data mode with createBrowserRouter, framework mode, or params in loaders.

Write :catId in the route and read it with useParams

First, write the parameter name in the route's path.

tsx
// App.tsx (excerpt)
import { Route, Routes } from 'react-router';
import { Cat } from './pages/Cat';

export default function App() {
  return (
    <Routes>
      <Route path="/cats/:catId" element={<Cat />} />
    </Routes>
  );
}

The declarative routing docs call a segment that starts with : a "dynamic segment". When a URL matches the route, the value of that part is passed to useParams and related APIs.

In the component, take the value out of the object returned by useParams() using the same name you wrote in path.

tsx
// pages/Cat.tsx (excerpt; the link and memo field are omitted)
import { useParams } from 'react-router';

export function Cat() {
  const { catId } = useParams();

  const id = Number(catId);
  const valid = Number.isInteger(id) && id > 0;

  return (
    <>
      <p>catId: {JSON.stringify(catId)}({typeof catId})</p>
      {valid ? <h1>猫の{id}番</h1> : <h1>「{catId}」は猫の番号ではありません</h1>}
    </>
  );
}

When I opened the page with different URLs, it displayed as follows.

URL opened Value of catId Heading
/cats/3 "3" (string) Cat #3
/cats/abc "abc" (string) "abc" is not a cat number
/cats/%E3%81%9F%E3%81%BE "たま" (string) "たま" is not a cat number
/cats/3/extra (the page is not displayed at all) None

Even when I opened /cats/3, catId was the string "3", not the number 3. If you want to use the ID as a number, convert it with Number() or similar, and prepare a display for values that are not digits. This page opens even for /cats/abc because the value only has to match the shape of the route, not be numeric.

When I opened the URL with the Japanese word for "Tama" percent-encoded as /cats/%E3%81%9F%E3%81%BE, catId contained the decoded value "たま". In the React Router source code, the path is decoded before it is matched against the routes. For decoding, it uses a function that splits the path at each / and applies decodeURIComponent to each part.

If you add an extra segment at the end, such as /cats/3/extra, it no longer matches /cats/:catId. No other route matched in this configuration, so the screen was empty, and the warning No routes matched location "/cats/3/extra" appeared in the console.

In TypeScript, the value type is string | undefined

The type of the value taken out with useParams() is string | undefined. When I assigned it directly to a variable of type string, the type check failed.

tsx
// typecheck/types-ng.tsx (excerpt)
const { catId } = useParams();
const id: string = catId;

The following output is the error for this case, one of three type-check errors.

text
typecheck/types-ng.tsx(5,9): error TS2322: Type 'string | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'.

Writing a type argument, such as useParams<{ catId: string }>() or useParams<'catId'>(), gave the same error. Looking at the type definitions in the useParams API reference, passing an object type adds Partial, and passing a name string gives a Params type where each value is string | undefined. Neither way removes undefined.

If you first exclude undefined, for example with if (catId === undefined) return null;, the rest of the code can treat the value as string, and the type check passed.

Reading multiple, optional, and * parameters

A single route can also have several parameters.

tsx
<Route path="/users/:userId/posts/:postId" element={<Post />} />
tsx
export function Post() {
  const { userId, postId } = useParams();
  return <h1>ユーザー {userId} の投稿 {postId}</h1>;
}

When I opened /users/7/posts/42, the heading showed the user ID 7 and the post ID 42 (the heading text is Japanese, meaning roughly "Post 42 by user 7"). The routing docs say not to reuse a parameter name within one path. If the same name appears twice, the later segment's value overwrites the earlier one.

Adding ? after a name makes that segment optional. This works for a part that may or may not be present, such as a language switch.

tsx
<Route path="/:lang?/categories" element={<Categories />} />
tsx
// excerpt (the line that displays the useParams() result is omitted)
export function Categories() {
  const params = useParams();
  const lang = params.lang ?? 'ja';
  return <h1>カテゴリー一覧({lang})</h1>;
}

For /en/categories, useParams() returned {"lang":"en"}, and the page displayed the heading for en. For /categories, it returned {}, so the lang key was missing entirely. The default ja set with ?? was used, and the page displayed the heading for ja.

As described in the splats section of the routing docs, if you put /* at the end of the path, everything after that point, including /, is captured together. The value is stored in params["*"]. When you destructure it, "*" cannot be used directly as a variable name, so you rename it.

tsx
<Route path="/files/*" element={<Files />} />
tsx
// excerpt (the line that displays the useParams() result is omitted)
export function Files() {
  const params = useParams();
  const { '*': filePath } = params;
  return <h1>ファイル:{filePath}</h1>;
}

When I opened /files/2026/11/neko.png, useParams() returned {"*":"2026/11/neko.png"}. The slashes in between are included in one string. When I opened only /files, the value was an empty string: {"*":""}. This pattern matches the Catchall Params example in the useParams API reference.

In nested routes, the parent can also see the child's parameters

When you nest routes, a child component can read the parent's parameters too. I tested this with a shop page that contains an item page.

tsx
<Route path="/shops/:shopId" element={<Shop />}>
  <Route path="items/:itemId" element={<Item />} />
</Route>
tsx
// pages/Shop.tsx (excerpt)
import { Outlet, useParams } from 'react-router';

export function Shop() {
  const params = useParams();
  return (
    <section>
      <h1>お店 {params.shopId}</h1>
      <p>Shop の useParams(): <code>{JSON.stringify(params)}</code></p>
      <Outlet />
    </section>
  );
}

export function Item() {
  const params = useParams();
  return (
    <section>
      <h2>商品 {params.itemId}(お店 {params.shopId})</h2>
      <p>Item の useParams(): <code>{JSON.stringify(params)}</code></p>
    </section>
  );
}

When I opened /shops/5/items/9, useParams() in the child Item returned {"shopId":"5","itemId":"9"}. As the useParams API reference explains, child routes inherit the parent's parameters.

Screenshot of /shops/5/items/9. The labels in the image are in Japanese; in English they read: heading "Shop 5", then the line "Shop useParams(): {"shopId":"5","itemId":"9"}", then heading "Item 9 (shop 5)", then the line "Item useParams(): {"shopId":"5","itemId":"9"}"
Opened /shops/5/items/9. The parent Shop and the child Item both receive the same shopId and itemId.

The parent Shop also returned {"shopId":"5","itemId":"9"} from useParams(), so the child route's itemId was included there too. When I opened only /shops/5, it returned {"shopId":"5"}, with no itemId. In the source code, the same object, which collects the parameters, is passed from the parent down to the child routes that match the URL. This means the parent component can tell whether a child page is open by checking whether params.itemId exists.

When only the ID changes, component state is kept

When navigation changes only a parameter within the same route, such as /cats/1 to /cats/2, the component is not recreated. The Cat component in my test also has a memo field and an effect (useEffect) that logs when catId changes. The first code sample omitted these.

tsx
const [memo, setMemo] = useState('');

useEffect(() => {
  console.log(`effect: catId=${catId}`);
}, [catId]);

// In the returned JSX
<input aria-label="メモ" value={memo} onChange={(e) => setMemo(e.target.value)} />

On /cats/1, I typed a memo saying the cat was already fed into the memo field, then moved to /cats/2 with a link on the page. The heading changed to "Cat #2". The effect, which depends on catId, ran again and logged effect: catId=2. However, the memo field still showed the same text. The memo written for cat 1 now appeared on the page for cat 2.

If you want to reset the state when the ID changes, pass the ID as a key so the component is recreated.

tsx
// Re-create Cat every time catId changes
export function CatKeyed() {
  const { catId } = useParams();
  return <Cat key={catId} />;
}
tsx
<Route path="/keyed/cats/:catId" element={<CatKeyed />} />

(In the test code, I passed one more prop to change the link destination inside Cat.)

When I typed a memo on /keyed/cats/1 and then moved to /keyed/cats/2, the memo field was empty. When key changes, React treats the component as a different one and recreates its state. This behavior is described in React's official documentation on resetting state with a key.

​Posted by 86