How to Use React Router

How to Use React Router: A Complete Tutorial Introduction React Router is an essential library for building single-page applications (SPAs) in React. It enables seamless navigation and dynamic routing within your application without requiring page reloads. By managing different routes, React Router allows developers to create rich, fluid user experiences that mimic traditional multi-page websites

Nov 17, 2025 - 11:09
Nov 17, 2025 - 11:09
 0

How to Use React Router: A Complete Tutorial

Introduction

React Router is an essential library for building single-page applications (SPAs) in React. It enables seamless navigation and dynamic routing within your application without requiring page reloads. By managing different routes, React Router allows developers to create rich, fluid user experiences that mimic traditional multi-page websites while maintaining the speed and responsiveness of SPAs.

Understanding how to use React Router effectively is crucial for any React developer aiming to build scalable and maintainable applications. This tutorial provides a comprehensive guide on using React Router, covering everything from basic setup to advanced routing strategies, best practices, and real-world examples.

Step-by-Step Guide

1. Installing React Router

To get started, you need to install the react-router-dom package, which provides the necessary components and hooks for web applications.

Run the following command in your project directory:

npm install react-router-dom

or if you prefer Yarn:

yarn add react-router-dom

2. Setting Up the Router

Wrap your application with the BrowserRouter component to enable routing based on the browser’s URL.

Example:

import { BrowserRouter } from 'react-router-dom';

function App() {

return (

<BrowserRouter>

<YourAppComponents />

</BrowserRouter>

);

}

3. Defining Routes

Use the Routes and Route components to declare URL paths and corresponding React components.

Example:

import { Routes, Route } from 'react-router-dom';

function App() {

return (

<BrowserRouter>

<Routes>

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

<Route path="/contact" element={<Contact />} />

</Routes>

</BrowserRouter>

);

}

4. Creating Navigation Links

React Router provides the Link component to navigate between routes without reloading the page.

Example:

import { Link } from 'react-router-dom';

function Navbar() {

return (

<nav>

<Link to="/">Home</Link>

<Link to="/about">About</Link>

<Link to="/contact">Contact</Link>

</nav>

);

}

5. Using URL Parameters

Dynamic routes allow you to capture values from the URL using parameters. Define parameters in the route path using a colon :.

Example route:

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

Access the parameter inside the component using the useParams hook:

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

function UserProfile() {

const { userId } = useParams();

return <p>User ID: {userId}</p>;

}

6. Navigating Programmatically

To navigate programmatically (e.g., after form submission), use the useNavigate hook.

import { useNavigate } from 'react-router-dom';

function Form() {

const navigate = useNavigate();

function handleSubmit(event) {

event.preventDefault();

// perform form logic

navigate('/thank-you');

}

return (

<form onSubmit={handleSubmit}>

<button type="submit">Submit</button>

</form>

);

}

7. Nested Routes

React Router supports nested routing, which allows you to define routes within routes to create layouts or subpages.

Example:

<Routes>

<Route path="/dashboard" element={<DashboardLayout />}>

<Route path="stats" element={<Stats />} />

<Route path="settings" element={<Settings />} />

</Route>

</Routes>

Inside DashboardLayout, render nested routes with the Outlet component:

import { Outlet } from 'react-router-dom';

function DashboardLayout() {

return (

<div>

<h1>Dashboard</h1>

<Outlet /> <!-- renders nested routes -->

</div>

);

}

8. Redirects and Handling 404s

To redirect users, use the Navigate component:

<Route path="/old-path" element={<Navigate to="/new-path" />} />

For handling unknown routes (404 pages), define a wildcard route:

<Route path="*" element={<NotFound />} />

Best Practices

1. Organize Routes Clearly

Keep your route definitions clean and organized, ideally in a dedicated file or folder. This improves maintainability and scalability.

2. Use Nested Routes for Layouts

Leverage nested routes to manage shared layouts or common UI sections, such as dashboards or user profiles.

3. Avoid Inline Functions in Route Elements

Define components separately rather than inline JSX in routes to improve readability and debugging.

4. Handle 404s Gracefully

Always include a fallback route to catch unmatched paths and display a user-friendly 404 page.

5. Leverage Code Splitting

Use React’s lazy loading and Suspense to load route components asynchronously, improving initial load time.

6. Keep URL Structure RESTful

Design routes that are intuitive and semantic, reflecting the hierarchy and type of content.

7. Use useNavigate and useParams Hooks Wisely

Utilize React Router hooks properly to enhance navigation and data extraction from URLs without prop drilling.

Tools and Resources

1. Official React Router Documentation

The best place to learn and reference React Router is its official documentation. It covers all APIs, examples, and migration guides.

2. React DevTools

React DevTools browser extension helps inspect the React component tree, including router components and props.

3. CodeSandbox and StackBlitz

Online editors like CodeSandbox and StackBlitz allow you to experiment with React Router code snippets quickly.

4. Tutorials and Courses

Platforms like Udemy, freeCodeCamp, and YouTube have comprehensive tutorials on React Router from beginner to advanced levels.

5. React Router GitHub Repository

Explore the source code and issues on the React Router GitHub repo to stay updated on latest features and community discussions.

Real Examples

Example 1: Basic Multi-Page SPA

This example demonstrates a simple React application with Home, About, and Contact pages using React Router.

import React from 'react';

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

function Home() { return <h2>Home Page</h2>; }

function About() { return <h2>About Us</h2>; }

function Contact() { return <h2>Contact</h2>; }

function App() {

return (

<BrowserRouter>

<nav>

<Link to="/">Home</Link> |

<Link to="/about">About</Link> |

<Link to="/contact">Contact</Link>

</nav>

<Routes>

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

<Route path="/contact" element={<Contact />} />

</Routes>

</BrowserRouter>

);

}

Example 2: User Profile with Dynamic Routes

Shows how to use URL parameters to display user-specific content.

import React from 'react';

import { BrowserRouter, Routes, Route, useParams, Link } from 'react-router-dom';

function UserProfile() {

const { userId } = useParams();

return <h2>Profile of User ID: {userId}</h2>;

}

function Users() {

return (

<div>

<h1>Users</h1>

<ul>

<li><Link to="/users/1">User 1</Link></li>

<li><Link to="/users/2">User 2</Link></li>

</ul>

</div>

);

}

function App() {

return (

<BrowserRouter>

<Routes>

<Route path="/users" element={<Users />} />

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

</Routes>

</BrowserRouter>

);

}

Example 3: Nested Routes with Layout

Illustrates route nesting to create a dashboard with multiple subpages.

import React from 'react';

import { BrowserRouter, Routes, Route, Outlet, Link } from 'react-router-dom';

function DashboardLayout() {

return (

<div>

<nav>

<Link to="stats">Stats</Link> |

<Link to="settings">Settings</Link>

</nav>

<Outlet />

</div>

);

}

function Stats() {

return <h2>Stats Page</h2>;

}

function Settings() {

return <h2>Settings Page</h2>;

}

function App() {

return (

<BrowserRouter>

<Routes>

<Route path="/dashboard" element={<DashboardLayout />}>

<Route path="stats" element={<Stats />} />

<Route path="settings" element={<Settings />} />

</Route>

</Routes>

</BrowserRouter>

);

}

FAQs

What is React Router used for?

React Router is used to implement client-side routing in React applications. It allows navigation between different views or pages without refreshing the entire page.

How do I install React Router?

Install React Router by running npm install react-router-dom or yarn add react-router-dom in your project folder.

What is the difference between BrowserRouter and HashRouter?

BrowserRouter uses the HTML5 history API for clean URLs, while HashRouter uses URL hash fragments (e.g.,

) and is useful for static file servers without server-side routing support.

How do I handle 404 pages in React Router?

Include a Route with path="*" at the end of your Routes to catch all unmatched URLs and render a 404 component.

Can I lazy load route components?

Yes, combine React’s lazy and Suspense with route elements to load components asynchronously and improve performance.

How do I pass props to a route component?

Instead of passing props directly in the element prop, define a wrapper component or use context/state to share data. React Router v6 no longer supports the render prop pattern.

Conclusion

React Router is a powerful routing library that enhances React applications by enabling dynamic, client-side navigation. Mastering its components and hooks allows developers to build user-friendly SPAs with intuitive URL structures and smooth transitions.

This tutorial covered fundamental concepts, practical implementation steps, best practices, useful tools, and real-world examples to help you confidently integrate React Router into your projects. By following these guidelines, you can create scalable, maintainable, and performant React applications with robust routing capabilities.