What Is React Router? Navigation for AI-Built Apps
TL;DR: React Router is the tool AI adds to your React app so users can navigate between pages — Home, About, Dashboard — without the browser reloading everything from scratch. It manages URLs, swaps page content instantly, and makes your single-page app feel like a real multi-page website. You'll see it in almost every AI-generated React project with more than one screen.
Why AI Coders Need to Understand React Router
Here's the scenario. You tell Claude or ChatGPT: "Build me a project management app with a dashboard, a projects page, and user settings." AI delivers a beautiful codebase. You run it. Everything works.
Then something breaks. Maybe clicking a link causes the whole page to flash white and reload. Maybe a URL like /projects/42 shows a blank page. Maybe you deploy to production and every page except the homepage gives you a 404 error.
All of these problems trace back to one thing: React Router.
If you've been working with React, you know it builds single-page applications — one HTML file that JavaScript manipulates to show different content. But "single page" doesn't mean "one screen." Your users expect to click around, see the URL change, hit the back button, and bookmark pages. That's what React Router handles.
Think of it like hallways in a building. The rooms are your pages — Home, About, Dashboard. React Router is the hallway system connecting them. Without it, every room is sealed off. Users can get in the front door, but they can't walk between rooms without going back outside and coming in through a different entrance (a full page reload).
Understanding React Router means you can:
- Read the code AI generates and know what each piece does
- Fix broken navigation when links don't work or pages go blank
- Debug 404 errors after deploying to production
- Tell AI exactly what you want when the default routing isn't right
The Real Scenario: What You Asked AI to Build
"Build me a React app for tracking home renovation projects. I need a homepage with an overview, a projects list page, individual project detail pages, and a settings page. Use modern React with hooks."
Standard request. Four different screens, navigation between them. AI generates a complete app and drops in React Router. Let's break down every piece.
What AI Generated: The Router Setup
Here's the core of what AI builds. This is typically in your App.jsx or main.jsx file — the central nervous system of your app's navigation:
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import Home from './pages/Home';
import Projects from './pages/Projects';
import ProjectDetail from './pages/ProjectDetail';
import Settings from './pages/Settings';
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
<Link to="/projects">Projects</Link>
<Link to="/settings">Settings</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/projects" element={<Projects />} />
<Route path="/projects/:id" element={<ProjectDetail />} />
<Route path="/settings" element={<Settings />} />
<Route path="*" element={<h1>Page Not Found</h1>} />
</Routes>
</BrowserRouter>
);
}
And here's what a typical page component looks like — the ProjectDetail page that shows a specific project:
import { useParams, useNavigate } from 'react-router-dom';
function ProjectDetail() {
const { id } = useParams();
const navigate = useNavigate();
return (
<div>
<button onClick={() => navigate('/projects')}>
← Back to Projects
</button>
<h1>Project #{id}</h1>
<p>Details for project {id} go here...</p>
</div>
);
}
That's it. That's the whole routing system. Now let's understand exactly what each piece does.
Understanding Each Part of React Router
BrowserRouter — The Foundation
Think of BrowserRouter as the building's foundation. Before you can have hallways, rooms, or doors, you need the foundation poured. BrowserRouter wraps your entire app and enables everything else to work.
<BrowserRouter>
{/* Everything in your app goes inside here */}
</BrowserRouter>
What it does: It watches the browser's URL bar. When the URL changes, it tells your app to show different content. It also manages the back and forward buttons.
What happens without it: Nothing works. Every other React Router piece — Routes, Link, useNavigate — needs BrowserRouter as an ancestor. Without it, you get: "useNavigate() may be used only in the context of a Router component."
Key rule: You only have one BrowserRouter in your entire app, and it wraps everything. Typically in App.jsx or main.jsx.
Routes and Route — The Floor Plan
If BrowserRouter is the foundation, Routes is the floor plan — the blueprint that says "when someone goes to this address, show them this room."
<Routes>
<Route path="/" element={<Home />} />
<Route path="/projects" element={<Projects />} />
<Route path="/projects/:id" element={<ProjectDetail />} />
<Route path="/settings" element={<Settings />} />
<Route path="*" element={<h1>Page Not Found</h1>} />
</Routes>
Each Route is a simple mapping:
path="/"→ When the URL is the homepage, show theHomecomponentpath="/projects"→ When the URL is/projects, show theProjectscomponentpath="/projects/:id"→ When the URL is/projects/followed by any value, show theProjectDetailcomponent (more on:idbelow)path="*"→ Anything that doesn't match the above? Show a "Page Not Found" message
The * catch-all route is like the "if all else fails" page. If someone types a random URL like /banana, they see your 404 message instead of a blank screen. AI doesn't always include this — if your app shows blank pages for wrong URLs, this is probably what's missing.
Link — The Doors Between Rooms
Link is how users walk between rooms without leaving the building. In plain HTML, you'd use an <a href="..."> tag. But in a React app, a regular anchor tag causes a full page reload — like leaving the building and walking back in through a different door.
{/* ❌ Regular HTML link — causes full page reload */}
<a href="/projects">View Projects</a>
{/* ✅ React Router Link — instant, no reload */}
<Link to="/projects">View Projects</Link>
What it does: When a user clicks a Link, React Router intercepts the click, updates the URL bar, and swaps out just the content that changed. The navigation bar stays put, any music keeps playing, form data on the page stays intact. It's fast and seamless.
Why this matters: If your app flashes white or loses state when you click around, check whether AI used regular <a> tags instead of <Link> components.
useNavigate — The Programmatic Redirect
Link works when users click something. But sometimes your app needs to redirect on its own — after a form submission, after a login, or when some condition is met. That's what useNavigate does.
import { useNavigate } from 'react-router-dom';
function LoginForm() {
const navigate = useNavigate();
const handleSubmit = (event) => {
event.preventDefault();
// ... login logic here ...
// After successful login, go to the dashboard
navigate('/dashboard');
};
return (
<form onSubmit={handleSubmit}>
{/* form fields */}
<button type="submit">Log In</button>
</form>
);
}
Common uses AI generates:
- Redirecting after form submission
- Sending unauthenticated users to a login page
- Going back:
navigate(-1)works like the browser back button - Replacing the current URL:
navigate('/new-page', { replace: true })— this replaces the current entry in browser history instead of adding a new one
useParams — Reading Dynamic URLs
Remember that :id in the route path? That colon means "this part is a variable." When the URL is /projects/42, the :id captures 42. useParams is how you read that value inside your component.
// Route definition:
<Route path="/projects/:id" element={<ProjectDetail />} />
// Inside ProjectDetail component:
function ProjectDetail() {
const { id } = useParams();
// If URL is /projects/42, then id = "42"
// If URL is /projects/7, then id = "7"
return <h1>Showing Project {id}</h1>;
}
This is like the room numbering system in a building. The hallway goes to "Room :number" — the actual number changes depending on where you're going, but the pattern is the same.
Important detail: useParams always returns strings. If you need a number (to fetch data from a database, for example), you'll need to convert it: const projectId = Number(id);. AI sometimes forgets this conversion, which can cause subtle bugs.
What AI Gets Wrong About React Router
AI is great at generating the initial router setup. But there are three mistakes it makes regularly. Knowing these saves you hours of debugging.
Mistake #1: Missing BrowserRouter Wrapper
This is the most common one. AI generates beautiful route definitions and Link components, but forgets to wrap the whole thing in BrowserRouter. Or it wraps the routes but puts the navigation outside the wrapper.
// ❌ Broken — Links are outside BrowserRouter
function App() {
return (
<div>
<nav>
<Link to="/">Home</Link> {/* 💥 Error! */}
</nav>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</BrowserRouter>
</div>
);
}
// ✅ Fixed — Everything inside BrowserRouter
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> {/* ✅ Works */}
</nav>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</BrowserRouter>
);
}
Error you'll see: "useHref() may be used only in the context of a <Router> component" or "Cannot read properties of null."
The fix: Tell AI: "Make sure BrowserRouter wraps the entire App component, including the navigation."
Mistake #2: Broken Nested Routes
When your app has sections with sub-pages — like a settings page with tabs for Profile, Notifications, and Security — AI needs to use nested routes. This is where it gets tricky.
// ❌ Broken — Settings sub-pages won't render
<Routes>
<Route path="/settings" element={<Settings />} />
<Route path="/settings/profile" element={<Profile />} />
<Route path="/settings/notifications" element={<Notifications />} />
</Routes>
// ✅ Correct — Nested routes with Outlet
<Routes>
<Route path="/settings" element={<Settings />}>
<Route index element={<Profile />} />
<Route path="notifications" element={<Notifications />} />
<Route path="security" element={<Security />} />
</Route>
</Routes>
In the correct version, the sub-routes are children of the settings route. The Settings component needs an <Outlet /> tag — a placeholder that says "render the child route's content here."
import { Outlet, Link } from 'react-router-dom';
function Settings() {
return (
<div>
<h1>Settings</h1>
<nav>
<Link to="/settings">Profile</Link>
<Link to="/settings/notifications">Notifications</Link>
<Link to="/settings/security">Security</Link>
</nav>
<Outlet /> {/* Child route content renders here */}
</div>
);
}
What to tell AI: "Use nested routes with an Outlet component for the settings section. I want the settings sidebar to stay visible while sub-pages change."
Mistake #3: 404 Errors on Page Refresh (The Big One)
This one catches everyone. Your app works perfectly in development. You click around, pages load, everything's smooth. Then you deploy it and refresh on /projects/42 — boom, 404 error.
Why this happens: React Router handles routing in the browser using JavaScript. When you first load the app, the server sends index.html, JavaScript boots up, and React Router takes over. But when you refresh, the browser asks the server for /projects/42. The server doesn't have a file at that path — it only has index.html.
Think of it this way: the building's internal directory (React Router) knows where Room 42 is. But the mailman (the server) only knows the building's street address. Tell the mailman to deliver to "Room 42" and they can't find it — they only know the main entrance.
The fix: Configure your server to send index.html for all routes. The specifics depend on your hosting:
# Netlify: create a _redirects file
/* /index.html 200
# Vercel: create a vercel.json
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}
# Apache: .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [L]
# Nginx:
location / {
try_files $uri /index.html;
}
What to tell AI: "I'm deploying to [Netlify/Vercel/my own server]. Add the server configuration needed so React Router works on refresh."
How to Debug React Router Issues
When navigation breaks in your AI-built app, here's the systematic approach. You don't need to understand the internal code — you need to know where to look.
Step 1: Check the Console
Open browser developer tools (right-click → Inspect → Console). React Router errors are usually clear. Look for messages mentioning "Router," "context," or "useNavigate." If you see an error you don't understand, paste it into your AI debugging tool — these errors are well-documented and AI excels at diagnosing them.
Step 2: Verify the BrowserRouter Wrapper
Open your App.jsx or main.jsx. Find <BrowserRouter>. Make sure it wraps everything — the navigation, the routes, all of it. If it's missing, add it. If it's in the wrong place, move it to the outermost position.
Step 3: Check for <a> Tags vs. <Link>
Search your codebase for <a href. Any anchor tag that points to an internal route (a page within your app) should be a <Link to> instead. External links to other websites can stay as regular anchor tags.
Step 4: Match Route Paths to Component Expectations
If a page shows blank or wrong content, compare the route's path to the URL you're visiting. A route of /projects/:id expects a URL like /projects/42 — not /projects/ (trailing slash can matter) or /project/42 (typo in the path).
Step 5: The Production Refresh Test
After deploying, navigate to any page using the app's links. Then refresh the browser. If you get a 404, you need the server redirect configuration from Mistake #3 above. This is the single most common React Router production issue.
The AI Debugging Prompt
"My React Router navigation is broken. Here's my App.jsx: [paste code]. The error I see is: [paste error]. I'm using React Router v6. What's wrong and how do I fix it?"
Always include your React Router version. V5 and v6 have different syntax, and AI will generate the wrong fix if it guesses wrong. Check package.json for "react-router-dom" to find your version.
What to Learn Next
You've unlocked one of the biggest pieces of AI-generated React code. Here's where to go next:
- What Is React? — If you jumped straight to routing, go back and understand the component model. Routing makes more sense when you understand how React builds UIs from pieces.
- What Is the DOM? — React Router manipulates the DOM to swap page content. Understanding the DOM helps you understand why single-page apps work the way they do.
- What Is Next.js? — Next.js has its own routing system built in. If AI starts generating Next.js projects for you, the routing works differently — and you don't need React Router at all.
- How to Debug AI-Generated Code — Routing errors are some of the most common bugs in AI-built apps. Learn the systematic approach to finding and fixing any issue.
- What Is JavaScript? — React Router is a JavaScript library. If you're fuzzy on how JavaScript works in the browser, this foundation will make everything click.
Frequently Asked Questions
What is React Router in simple terms?
React Router is a library that lets your React app switch between different pages — like Home, About, and Dashboard — without reloading the entire browser window. It makes a single-page app feel like a traditional multi-page website by swapping content instantly when users click links.
Why does AI always add React Router to my project?
When you ask AI to build an app with multiple pages or screens, it needs a way to handle navigation. React Router is the most popular routing library for React with millions of weekly downloads, so AI defaults to it. If your app only has one page, you probably don't need it.
What is the difference between Link and a regular anchor tag?
A regular HTML anchor tag (<a href>) causes a full page reload — the browser fetches everything from scratch. React Router's Link component intercepts that click and swaps just the content that changed, keeping the rest of the page intact. It's faster and preserves your app's state (like form data or scroll position).
Why do I get a 404 error when I refresh a React Router page?
React Router handles URLs on the client side (in the browser). When you refresh, the browser asks the server for that URL — but the server only has index.html. You need to configure your server to send index.html for all routes. In development, most setups handle this automatically, but in production you need a redirect rule or server config change.
Do I need React Router if I'm using Next.js?
No. Next.js has its own built-in routing system based on the file system — you create a file in the pages or app directory and it automatically becomes a route. If AI generates React Router code inside a Next.js project, that's a mistake. Tell AI to use Next.js's built-in router instead.