React Router — Detailed Notes
1. Overview
React Router is a library for routing in React applications. It enables navigation between views or
pages without refreshing the browser. It handles dynamic URL matching, nested routing, redirects,
and protected routes.
2. Core Concepts
a. Single Page Application (SPA)
React Router allows SPAs to simulate multiple pages by conditionally rendering components based
on the URL path. The browser does not reload; only the component tree updates.
b. Client-Side Routing
Instead of sending a request to the server for each URL, React Router intercepts navigation and
renders the appropriate component in the browser using JavaScript.
3. Installation
npm install react-router-dom
4. Important Components
a. <BrowserRouter>
• The root component wrapping the entire app.
• Uses the HTML5 History API to keep UI in sync with the URL.
• Commonly placed at the top level (usually in [Link] or [Link]).
import { BrowserRouter } from "react-router-dom";
<BrowserRouter>
<App />
</BrowserRouter>
b. <Routes>
• A container for all route definitions.
• React Router v6 replaced <Switch> with <Routes>.
• Ensures that only one matching route is rendered at a time.
import { Routes, Route } from "react-router-dom";
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
c. <Route>
• Defines a mapping between a path and a component.
• Uses the element prop to specify which component to render.
• Supports nested routes and dynamic parameters.
<Route path="/user/:id" element={<UserProfile />} />
d. <Link>
• Used for internal navigation.
• Prevents full page reload.
• Uses to prop for path navigation.
<Link to="/about">About</Link>
e. <NavLink>
• Similar to <Link>, but can apply an active class or style when the link matches the current
route.
• Commonly used for navigation menus.
<NavLink to="/home" className={({ isActive }) => isActive ? "active" : ""}>
Home
</NavLink>
f. <Navigate>
• Used for programmatic redirection.
• Replaces <Redirect> in v6.
<Navigate to="/login" replace />
g. useNavigate()
• A hook for navigation inside functions or components.
const navigate = useNavigate();
navigate("/profile");
h. useParams()
• Access route parameters in dynamic routes.
const { id } = useParams();
i. useLocation()
• Provides information about the current URL location (pathname, search params, etc.).
const location = useLocation();
[Link]([Link]);
j. useSearchParams()
• Manage query parameters in the URL.
const [searchParams, setSearchParams] = useSearchParams();
const name = [Link]("name");
5. Nested Routes
Allows hierarchical UI rendering (e.g., dashboard with sidebar and inner pages).
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
To render nested components, use the <Outlet /> inside the parent:
const Dashboard = () => (
<div>
<Sidebar />
<Outlet />
</div>
);
6. Protected Routes
Used to restrict access to certain paths (e.g., /dashboard for authenticated users).
const ProtectedRoute = ({ children }) => {
const isAuthenticated = [Link]("auth");
return isAuthenticated ? children : <Navigate to="/login" />;
};
// Usage
<Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
7. Programmatic Navigation
For dynamic redirects after actions like login or form submission.
const navigate = useNavigate();
navigate("/home", { replace: true });
8. Route Parameters and Query Strings
Dynamic Parameters
<Route path="/user/:id" element={<User />} />
Access using:
const { id } = useParams();
Query Strings
const [searchParams, setSearchParams] = useSearchParams();
const filter = [Link]("filter");
9. Lazy Loading and Code Splitting
React Router supports [Link]() and Suspense to optimize performance.
const About = [Link](() => import("./About"));
<Routes>
<Route path="/about" element={
<Suspense fallback={<div>Loading...</div>}>
<About />
</Suspense>
} />
</Routes>
10. Error Handling with Fallback Routes
Use a catch-all route for 404 pages.
<Route path="*" element={<NotFound />} />
11. Navigation from Code (Hooks)
Hook Purpose
useNavigate() Navigate programmatically
useParams() Access URL parameters
useLocation() Get current route info
useSearchParams() Manage query strings
12. Router Types
Router Description
BrowserRouter Uses HTML5 history API (recommended)
HashRouter Uses URL hash (/#/) for older browsers or static file servers
MemoryRouter Stores history in memory (used in tests)
13. Route Configuration Object (v6.4+)
React Router supports declarative route configuration.
const router = createBrowserRouter([
path: "/",
element: <App />,
children: [
{ path: "about", element: <About /> },
{ path: "contact", element: <Contact /> },
],
},
]);
<RouterProvider router={router} />
14. Data APIs (v6.4+)
Newer versions support data loading, actions, and error handling within routes.
path: "/user/:id",
element: <User />,
loader: async ({ params }) => fetch(`/api/user/${[Link]}`),