Docs
Core Concepts
Routing
Dynamic Routes

Dynamic Routes

Dynamic Routes are routes that are generated at runtime. This is useful when you have a large number of pages that are similar, but not exactly the same. For example, you might want to create a page for each user on your website. Instead of creating a page for each user, you can create a single page that uses a dynamic route to load the user's data.

Example

Here is an example of a Dynamic Route to display a user's profile page.

In the example above, we have created a Dynamic Route to display a user's profile page. The :id in the route path is a dynamic parameter that can be used to load the user's data based on his userId.

Accessing Dynamic Route Parameters

To access the dynamic route parameters, you can use the useParams hook.

useParams returns an object containing the dynamic route parameters. You can learn more about useParams on React Router docs (opens in a new tab).

Dynamic Route with Optional Parameters

You can also create a Dynamic Route with optional parameters.

In the example above, we have created a Dynamic Route with an optional parameter. The ? at the end of the route parameter makes it optional.

By doing like this, when we access the /profile route, the id will be undefined and we won't get a 404 error. But in the case where the id is not optional, navigating to /profile will result in a 404 error.

You can have optional static segments too.

src/app/profile.page.tsx
Profile.path = "/profile/:id?/edit?";

Dynamic Route with Multiple Parameters

You can also create a Dynamic Route with multiple parameters.

You can chain multiple parameters in a Dynamic Route by separating them with a /.

Next steps

Introduction to Rendering
Logo Image