React: From Components to Production · Routing with React Router
React Router Basics
Define routes, link between pages and read URL parameters.
React Router (v7) maps URLs to components. In data mode you create a router with createBrowserRouter and render <RouterProvider>; in declarative mode you use <BrowserRouter> with <Routes>. Navigate with <Link>/<NavLink> (no full page reloads) or useNavigate(), and read dynamic segments with useParams(). In v7 everything is imported from react-router.
import { createBrowserRouter, RouterProvider, Link, useParams } from "react-router";
function ProductPage() {
const { productId } = useParams(); // "/products/42" → "42"
return <h1>Product {productId}</h1>;
}
const router = createBrowserRouter([
{ path: "/", element: <Home /> },
{ path: "/products/:productId", element: <ProductPage /> },
{ path: "*", element: <NotFound /> },
]);
export function App() {
return <RouterProvider router={router} />;
}
// Navigation
<Link to="/products/42">View product</Link>
Common pitfalls
- Using
<a href>for internal links, causing full page reloads. - Forgetting a catch-all 404 route.
- Treating
useParams()values as numbers — they're strings (or undefined).
Key points
- Routes map URLs to components
- Link avoids full reloads
- Params are strings
Further reading: React Router: routing
Practice questions
Why use <Link> instead of <a href> for internal navigation?
Answer
Link updates the URL with the History API and renders the new route client-side, keeping app state and avoiding a full page reload.
What type does useParams() return for :id?
Answer
A string (or undefined), even if the URL segment looks numeric. Parse and validate it yourself.
Open in the app to mark lessons complete, take notes and track your progress.