|
1 | 1 | --- |
2 | 2 | title: useParams |
3 | | -use_cases: 'dynamic routes, user profiles, product pages, id-based content, url parameters' |
| 3 | +use_cases: "dynamic routes, user profiles, product pages, id-based content, url parameters" |
4 | 4 | tags: |
5 | 5 | - params |
6 | 6 | - dynamic |
7 | 7 | - routes |
8 | 8 | - parameters |
9 | 9 | - reactive |
10 | | -version: '1.0' |
| 10 | +version: "1.0" |
11 | 11 | description: >- |
12 | 12 | Access route parameters reactively with useParams - extract dynamic segments |
13 | 13 | from URLs for user profiles, products, and ID-based pages. |
14 | 14 | --- |
15 | 15 |
|
16 | | -`useParams` retrieves a reactive object similar to a store. |
17 | | -It contains the current route's path parameters as defined in the Route. |
| 16 | +The `useParams` function reads the path parameters of the current route. |
18 | 17 |
|
19 | | -```js |
20 | | -const params = useParams(); |
| 18 | +## Import |
21 | 19 |
|
22 | | -// Route path: /user/:id => /user/123 |
23 | | -console.log(params.id); // 123 |
| 20 | +```ts |
| 21 | +import { useParams } from "@solidjs/router"; |
24 | 22 | ``` |
| 23 | + |
| 24 | +## Type |
| 25 | + |
| 26 | +```ts |
| 27 | +function useParams<T extends Record<string, string>>(): T; |
| 28 | +``` |
| 29 | + |
| 30 | +## Parameters |
| 31 | + |
| 32 | +`useParams` takes no arguments. |
| 33 | + |
| 34 | +## Return value |
| 35 | + |
| 36 | +- **Type**: `T` |
| 37 | + |
| 38 | +`useParams` returns a reactive object where keys match the dynamic segments defined in the route path. |
| 39 | +Accessing a property within a tracking scope registers a dependency, causing the computation to re-run when the parameter changes. |
| 40 | + |
| 41 | +## Examples |
| 42 | + |
| 43 | +### Basic usage |
| 44 | + |
| 45 | +```ts |
| 46 | +import { createMemo } from "solid-js"; |
| 47 | +import { useParams } from "@solidjs/router"; |
| 48 | + |
| 49 | +// Rendered via <Route path="/users/:id" component={UserPage} /> |
| 50 | +function UserPage() { |
| 51 | + const params = useParams(); |
| 52 | + |
| 53 | + // Derived value updates when the route parameter changes. |
| 54 | + const title = createMemo(() => `Profile for ${params.id}`); |
| 55 | + |
| 56 | + return <h1>{title()}</h1>; |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +## Related |
| 61 | + |
| 62 | +- [useLocation](/solid-router/reference/primitives/use-location) |
| 63 | +- [useSearchParams](/solid-router/reference/primitives/use-search-params) |
0 commit comments