React / 38
Dynamic routes: useParams & useNavigate
One route like /menu/:id serves every dish. Read the id with useParams, link to it with a template string, and move users in code with useNavigate.
A dynamic segment
A path segment that starts with : is a dynamic segment. It matches any value in that slot:
{ path: "menu/:id", element: <Dish /> }route pattern
menu/:id
const params = useParams()
{ id: "42" }effect
fetch(`https://dummyjson.com/recipes/${id}`)Read it with useParams
import { useEffect, useState } from "react";
import { useParams } from "react-router";
export default function Dish() {
const { id } = useParams(); // "/menu/7" → { id: "7" }
const [dish, setDish] = useState(null);
useEffect(() => {
let ignore = false;
fetch(`https://dummyjson.com/recipes/${id}`)
.then((res) => res.json())
.then((data) => {
if (!ignore) setDish(data);
});
return () => {
ignore = true;
};
}, [id]);
// no data yet, or still the previous dish: we're loading
if (!dish || String(dish.id) !== id) return <p>Loading…</p>;
return <h1>{dish.name}</h1>;
}Three details that matter:
[id]in the dependencies. Going from/menu/7to/menu/8doesn't unmountDish, it just re-renders it with a newid. With[], it would keep showing dish 7.- The
ignoreflag. Click quickly through dishes and the responses can arrive out of order. The cleanup drops the stale ones (see Fetching data with useEffect). String(dish.id) !== id. The URL param is a string, the API's id is a number. Comparing them shows "Loading…" instead of the old dish while the new one arrives.
Link to it
Build the URL with a template string:
<ul>
{recipes.map((recipe) => (
<li key={recipe.id}>
<Link to={`/menu/${recipe.id}`}>{recipe.name}</Link>
</li>
))}
</ul>More patterns you'll meet:
| Path | URL | useParams() |
|---|---|---|
menu/:id | /menu/42 | { id: "42" } |
users/:userId/orders/:orderId | /users/7/orders/99 | { userId: "7", orderId: "99" } |
docs/* | /docs/a/b | { "*": "a/b" } |
Navigate in code with useNavigate
Sometimes you move the user because something happened, not because they clicked a link: an order went through, a login worked. useNavigate() gives you a function for that:
import { useNavigate } from "react-router";
export default function Checkout({ placeOrder }) {
const navigate = useNavigate();
async function handleSubmit(e) {
e.preventDefault();
await placeOrder();
navigate("/orders/thanks", { replace: true });
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Place order</button>
<button type="button" onClick={() => navigate(-1)}>Back</button>
</form>
);
}navigate("/path")goes there, like a link click.{ replace: true }replaces the current history entry, so Back doesn't return to a submitted form.navigate(-1)goes back one step, like the browser's Back button.
Don't
useNavigate for ordinary links
<button onClick={() => navigate("/menu")}>Menu</button>No real href: no Ctrl/Cmd-click to open in a new tab, no link preview, and screen readers announce it as a button.
Do
Link for links, navigate for events
<Link to="/menu">Menu</Link>Use navigate only after something happens: a submit, a login, a timeout.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
