Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.3 — Dynamic Segments, Params and Search Params
React · Example 1 of 3

useParams: one route, many products

The param arrives as the string "2", so the code converts it with Number. Users can type any URL, so /products/99 shows a friendly not-found message instead of crashing on product.name.

A dynamic segment like /products/:productId lets one route serve every product and useParams() reads the value; useSearchParams() reads and writes the ?key=value part for filters and sorting; useNavigate() moves the user from code, and useLocation() tells you exactly where you are.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Create a route /users/:userId/posts/:postId and a component that prints both params, with links to /users/1/posts/10 and /users/2/posts/20.

02

Build a search page where typing in an input updates ?q= with replace: true and the list shows only fruit names containing q.

03

After a fake login button is clicked, navigate to /dashboard with replace: true and show Welcome back from location state.

Explain it without notes

01

What is a dynamic segment, and what does useParams() return for it?

02

Why must you validate params, and what are the usual mistakes?

03

How does useSearchParams work, and why should filters live there instead of in useState?

04

When do you use useNavigate instead of <Link>, and what do replace and state do?

useParams: one route, many products

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

productId: "2" found: Desk lamp
productId: "99" found: nothing