DevAcademy
LearnReactReact Router
AdvancedReact

React Router

Learn how to add client-side routing to a React app using React Router.

Reading Time

20 min

Lesson

Lesson 34 of 42

Why a Router?

React itself has no concept of URLs or navigation. React Router is the most widely used library for mapping URL paths to components, enabling multi-page-feeling apps that never actually reload the page.

Installing React Router

npm install react-router-dom

Basic Route Setup

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

Dynamic Route Parameters

A route path can include a parameter (prefixed with :), and useParams() reads its current value inside the matched component.

Dynamic Route with useParams

import { useParams } from "react-router-dom";

<Route path="/users/:userId" element={<UserProfile />} />;

function UserProfile() {
  const { userId } = useParams();
  return <h1>Viewing user {userId}</h1>;
}

Programmatic Navigation

The useNavigate hook lets you navigate imperatively from inside event handlers or effects — for example, redirecting after a successful form submission.

Frameworks Often Handle Routing Differently

Full-stack React frameworks like Next.js use file-based routing instead of declaring <Route> components manually — the folder structure under an app or pages directory determines the URL structure automatically.

Best Practice

Keep route definitions in one central place (or a small number of route files) rather than scattering <Route> elements throughout the codebase — it keeps the app’s overall URL structure easy to see at a glance.

Interview Questions

Quick Quiz

1. What does the Link component do differently from a regular <a> tag?

2. Which hook reads a dynamic route parameter like :userId?

3. Which hook lets you navigate to a new route from inside an event handler?