React Router Basics

📘 React.js 👁 40 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

React Router is a library used to handle client-side routing in React applications. It allows you to create multiple pages without reloading the browser.


Why Use React Router?

  • Enables navigation in single-page applications (SPA)

  • Updates the URL without page refresh

  • Maps URLs to React components

  • Improves user experience


Installation

npm install react-router-dom

Basic Setup

Wrap your app with BrowserRouter.

import { BrowserRouter } from "react-router-dom"; function App() { return ( <BrowserRouter> <Routes /> </BrowserRouter> ); }

Defining Routes

import { Routes, Route } from "react-router-dom"; function RoutesConfig() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes> ); }

Navigation with Link

import { Link } from "react-router-dom"; function Navbar() { return ( <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> ); }

useParams (URL Parameters)

import { useParams } from "react-router-dom"; function User() { const { id } = useParams(); return <p>User ID: {id}</p>; }

Route:

<Route path="/user/:id" element={<User />} />

useNavigate (Programmatic Navigation)

import { useNavigate } from "react-router-dom"; function Login() { const navigate = useNavigate(); function handleLogin() { navigate("/dashboard"); } return <button onClick={handleLogin}>Login</button>; }

Nested Routes

<Route path="/dashboard" element={<Dashboard />}> <Route path="profile" element={<Profile />} /> <Route path="settings" element={<Settings />} /> </Route>

Use inside Dashboard.


404 Page (Not Found)

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

Common Hooks

HookPurpose
useParamsRead URL params
useNavigateNavigate programmatically
useLocationAccess current location

Best Practices

  • Keep routes organized

  • Use layout components

  • Lazy load routes when needed

  • Use meaningful URLs


Key Points

  • React Router handles SPA routing

  • BrowserRouter wraps the app

  • Routes and Route define paths

  • Hooks enable dynamic navigation


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes