Skip to content
ClapelloNotes by Barath
ReactCh 07 · 5/6
Core4 min readUpdated

React / 38

Dynamic routes: useParams & useNavigate

TL;DR

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 /> }
example.com/menu/42
router compares it with each pattern

route pattern

menu/:id

menu = menu:id = 42
inside <Dish />

const params = useParams()

{ id: "42" }
use it

effect

fetch(`https://dummyjson.com/recipes/${id}`)
The :id part of the pattern matches any value in that slot. useParams() hands it to you, always as a string.

Read it with useParams

pages/Dish.jsx
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/7 to /menu/8 doesn't unmount Dish, it just re-renders it with a new id. With [], it would keep showing dish 7.
  • The ignore flag. 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.

Build the URL with a template string:

pages/Menu.jsx
<ul>
  {recipes.map((recipe) => (
    <li key={recipe.id}>
      <Link to={`/menu/${recipe.id}`}>{recipe.name}</Link>
    </li>
  ))}
</ul>

More patterns you'll meet:

PathURLuseParams()
menu/:id/menu/42{ id: "42" }
users/:userId/orders/:orderId/users/7/orders/99{ userId: "7", orderId: "99" }
docs/*/docs/a/b{ "*": "a/b" }

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:

pages/Checkout.jsx
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.