đ React Router v6 Kya Hai?
React Router ek powerful library hai jo aapke React application mein client-side routing implement karne mein help karti hai. Iska matlab hai ki aap bina page reload kiye different views/pages ke beech navigate kar sakte ho. Version 6 mein bahut saare improvements aur simplified APIs aaye hain jo development ko aur bhi easy banate hain.
Key Features:
- Declarative Routing: Routes ko JSX components ki tarah define karo
- Nested Routes: Routes ke andar routes banao
- Dynamic Routing: URL parameters ke saath flexible routing
- Code Splitting: Lazy loading se performance improve karo
- Protected Routes: Authentication-based access control
đĄ Pro Tip: React Router v6 ne v5 se kaafi changes kiye hain.
Switch ab Routes ban gaya hai, aur component prop ab element prop ban gaya hai.
1ī¸âŖ Creating Routes (Basic Setup)
Routes create karna bahut simple hai. Sabse pehle aapko
BrowserRouter se apne app ko wrap karna hota hai, phir Routes aur Route components use karke individual routes define karte hain.
// App.js
import { BrowserRouter, 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>
);
}
đŽ Interactive Demo: Basic Routing
đ Home Page
Welcome to the home page! Yeh aapka landing page hai.
2ī¸âŖ Nested Routes
Nested Routes ka matlab hai routes ke andar routes. Jaise agar aapke paas ek
/dashboard route hai, aur uske andar /dashboard/profile aur /dashboard/settings chahiye, toh nested routes use karte hain. Isse aapka code organized aur maintainable rehta hai.
// Nested Routes Example
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
<Route path="analytics" element={<Analytics />} />
</Route>
</Routes>
// Dashboard.js - Parent component mein Outlet use karo
import { Outlet } from 'react-router-dom';
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Outlet /> {/* Nested routes yahan render honge */}
</div>
);
}
đŽ Interactive Demo: Nested Routes Visualizer
đ / (Root)
đ /dashboard
đ /dashboard/profile
đ /dashboard/settings
đ /dashboard/analytics
Selected Route: /
â ī¸ Important: Parent route component mein
<Outlet /> component use karna zaroori hai, warna nested routes render nahi honge!
3ī¸âŖ Layout Routes
Layout Routes ek special type ke routes hain jo common layout provide karte hain multiple pages ke liye. Jaise agar aapko har page pe same navbar aur footer chahiye, toh layout route use karo. Isse code duplication kam hota hai aur maintenance easy ho jata hai.
// Layout Component
import { Outlet } from 'react-router-dom';
function Layout() {
return (
<div>
<Navbar />
<main>
<Outlet /> {/* Child routes yahan render honge */}
</main>
<Footer />
</div>
);
}
// Routes with Layout
<Routes>
<Route element={<Layout />}>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Route>
</Routes>
đŽ Interactive Demo: Layout Routes
đ§ Navbar (Layout - Always Visible)
đ Home Content
Yeh content change hota hai, but navbar aur footer same rehte hain!
đ§ Footer (Layout - Always Visible)
4ī¸âŖ Route Parameters (Dynamic Routes)
Route Parameters se aap dynamic URLs create kar sakte ho. Jaise
/user/123 ya /product/laptop. Yeh parameters useParams hook se access kar sakte ho. Isse ek hi component multiple IDs ke liye reuse ho sakta hai.
// Route with parameter
<Route path="/user/:userId" element={<UserProfile />} />
<Route path="/product/:productId" element={<ProductDetail />} />
// UserProfile.js - useParams hook se parameter access karo
import { useParams } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams();
return (
<div>
<h1>User Profile</h1>
<p>User ID: {userId}</p>
</div>
);
}
đŽ Interactive Demo: Route Parameters
Click on any user card to see dynamic routing in action:
đ¤ User 101
Rajesh Kumar
đ¤ User 102
Priya Sharma
đ¤ User 103
Amit Patel
Current Route: /user/-
useParams() returns:
useParams() returns:
{ }
đĄ Multiple Parameters: Aap ek route mein multiple parameters bhi use kar sakte ho:
/blog/:category/:postId â { category: 'tech', postId: '123' }
5ī¸âŖ Search Params (Query Parameters)
Search Parameters wo query strings hain jo URL mein
? ke baad aate hain. Jaise /products?category=electronics&sort=price. Inhe useSearchParams hook se manage karte hain. Yeh filtering, sorting, pagination ke liye bahut useful hain.
// useSearchParams hook
import { useSearchParams } from 'react-router-dom';
function Products() {
const [searchParams, setSearchParams] = useSearchParams();
const category = searchParams.get('category');
const sort = searchParams.get('sort');
const updateFilter = (key, value) => {
setSearchParams({ [key]: value });
};
return (
<div>
<p>Category: {category}</p>
<p>Sort: {sort}</p>
</div>
);
}
đŽ Interactive Demo: Search Parameters
đī¸ Products Page
Current Search Params:
{ }
6ī¸âŖ Protected Routes + Auth Guard
Protected Routes wo routes hain jo sirf authenticated users access kar sakte hain. Agar user logged in nahi hai, toh use login page pe redirect kar dete hain. Isse aap apne sensitive pages ko secure kar sakte ho. Yeh authentication aur authorization ke liye bahut important hai.
// ProtectedRoute Component
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const isAuthenticated = checkAuth(); // Your auth logic
return isAuthenticated ? children : <Navigate to="/login" />;
}
// Usage in Routes
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
</Routes>
đŽ Interactive Demo: Protected Routes
đ Authentication Panel
â Not Logged In
đ Try Accessing Protected Page
Click "Go to Dashboard" to test protected route...
â ī¸ Security Note: Client-side protection sirf UI ke liye hai. Real security backend/API level pe implement karni chahiye!
7ī¸âŖ Lazy Loading Routes (Code Splitting)
Lazy Loading se aap apne components ko on-demand load kar sakte ho. Isse initial bundle size kam hota hai aur app faster load hoti hai. React ke
lazy() aur Suspense ke saath use karte hain. Yeh performance optimization ke liye bahut important hai.
// Lazy loading with React.lazy()
import { lazy, Suspense } from 'react';
const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Profile = lazy(() => import('./pages/Profile'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</Suspense>
);
}
đŽ Interactive Demo: Lazy Loading
Click buttons to simulate lazy loading of components:
No component loaded yet. Click a button to see lazy loading in action!
đ Bundle Size Impact:
Initial Bundle: 250 KB
Loaded Chunks: 0
Initial Bundle: 250 KB
Loaded Chunks: 0
đĄ Best Practice: Heavy components (charts, editors, large libraries) ko lazy load karo. Small components ko lazy load karne se overhead badh sakta hai.
8ī¸âŖ Relative Link Paths
Relative Paths se aap current route ke relative links create kar sakte ho. Isse code maintainable rehta hai aur refactoring easy ho jata hai.
Link aur useNavigate dono mein relative paths use kar sakte ho.
// Relative paths in nested routes
import { Link, Outlet } from 'react-router-dom';
function Dashboard() {
return (
<div>
<nav>
{/* Relative to current route */}
<Link to="profile">Profile</Link>
<Link to="settings">Settings</Link>
{/* Go up one level */}
<Link to="..">Back</Link>
</nav>
<Outlet />
</div>
);
}
đŽ Interactive Demo: Relative Paths
Current Location:
/dashboard
Navigation Result:
/dashboard
đĄ Path Types:
âĸ
âĸ
âĸ
âĸ
âĸ
"profile" â Relative to current routeâĸ
"./profile" â Same as aboveâĸ
"../profile" â Go up one level, then to profileâĸ
"/profile" â Absolute path from root
9ī¸âŖ Programmatic Navigation
Programmatic Navigation ka matlab hai code se navigation karna, bina user ke link click kiye. Jaise form submit ke baad redirect karna, ya authentication ke baad dashboard pe bhejna.
useNavigate hook se yeh karte hain.
// useNavigate hook for programmatic navigation
import { useNavigate } from 'react-router-dom';
function LoginForm() {
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
const success = await login(credentials);
if (success) {
// Navigate to dashboard
navigate('/dashboard');
// Navigate with replace (no back button)
navigate('/dashboard', { replace: true });
// Navigate back
navigate(-1);
// Navigate forward
navigate(1);
}
};
return <form onSubmit={handleSubmit}>...</form>;
}
đŽ Interactive Demo: Programmatic Navigation
Navigation History:
Current Position: 1 / 1
â ī¸ Replace vs Push:
âĸ
âĸ
âĸ
navigate('/path') â History mein add hota hai (back button kaam karega)âĸ
navigate('/path', {replace: true}) â Current entry replace ho jati hai (back button previous page pe nahi jayega)
đ¯ Interview Questions
Yeh questions aapki React Router v6 understanding ko test karenge. Har question ke answer ko toggle kar sakte ho.
Easy
Q1: React Router v6 mein Switch component ko kya replace karta hai aur kyun?
Answer: React Router v6 mein
1. Better Naming: "Routes" naam zyada descriptive hai
2. Relative Routing: Routes component relative routing ko better support karta hai
3. Route Ranking: Automatic route ranking system hai jo best match find karta hai
4. Nested Routes: Nested routes ko handle karna zyada easy ho gaya hai
Switch component ko Routes component ne replace kar diya hai. Yeh change isliye kiya gaya kyunki:1. Better Naming: "Routes" naam zyada descriptive hai
2. Relative Routing: Routes component relative routing ko better support karta hai
3. Route Ranking: Automatic route ranking system hai jo best match find karta hai
4. Nested Routes: Nested routes ko handle karna zyada easy ho gaya hai
<Switch> (v5) â <Routes> (v6)
Easy
Q2: useParams hook ka kya use hai? Example ke saath explain karo.
Answer:
Example:
Route:
URL:
useParams hook URL parameters ko access karne ke liye use hota hai. Jab aap dynamic routes banate ho, tab yeh hook un parameters ko extract karta hai.Example:
Route:
/user/:userId/post/:postIdURL:
/user/123/post/456
const { userId, postId } = useParams();
// userId = "123"
// postId = "456"
Use Cases: User profiles, product details, blog posts, etc.
Medium
Q3: Protected Routes ko implement karne ke different approaches kya hain? Pros aur cons discuss karo.
Answer: Protected Routes implement karne ke 3 main approaches hain:
1. Wrapper Component Approach:
â Cons: Extra component wrapper
2. Higher Order Component (HOC):
â Cons: Wrapper hell, debugging difficult
3. Layout Route with Outlet:
â Cons: Initial setup thoda complex
1. Wrapper Component Approach:
<ProtectedRoute><Dashboard /></ProtectedRoute>â Pros: Reusable, clean syntax
â Cons: Extra component wrapper
2. Higher Order Component (HOC):
const ProtectedDashboard = withAuth(Dashboard);â Pros: Composition pattern, flexible
â Cons: Wrapper hell, debugging difficult
3. Layout Route with Outlet:
<Route element={<AuthLayout />}>
<Route path="/dashboard" element={<Dashboard />} />
</Route>
â
Pros: Scalable, multiple routes protect kar sakte hoâ Cons: Initial setup thoda complex
Medium
Q4: Lazy loading routes se performance kaise improve hoti hai? Trade-offs kya hain?
Answer: Lazy loading se performance improvement:
Benefits:
1. Reduced Initial Bundle: Starting mein sirf required code load hota hai
2. Faster First Paint: Page jaldi render hota hai
3. Better Caching: Individual chunks cache ho sakte hain
4. On-Demand Loading: User jab route visit kare tabhi load ho
Trade-offs:
1. Loading Delay: First time route visit pe delay ho sakta hai
2. Network Requests: Extra network calls
3. Complexity: Error handling aur loading states manage karne padte hain
4. Suspense Required: Fallback UI provide karna zaroori hai
Best Practice: Heavy components (admin panels, dashboards, editors) ko lazy load karo, frequently used components ko nahi.
Benefits:
1. Reduced Initial Bundle: Starting mein sirf required code load hota hai
2. Faster First Paint: Page jaldi render hota hai
3. Better Caching: Individual chunks cache ho sakte hain
4. On-Demand Loading: User jab route visit kare tabhi load ho
Trade-offs:
1. Loading Delay: First time route visit pe delay ho sakta hai
2. Network Requests: Extra network calls
3. Complexity: Error handling aur loading states manage karne padte hain
4. Suspense Required: Fallback UI provide karna zaroori hai
Best Practice: Heavy components (admin panels, dashboards, editors) ko lazy load karo, frequently used components ko nahi.
Medium
Q5: useSearchParams aur useParams mein kya difference hai? Kab kaunsa use karoge?
Answer:
useParams:
âĸ URL path segments se data extract karta hai
âĸ Route definition mein define hota hai:
âĸ Read-only hai
âĸ Example:
useSearchParams:
âĸ Query strings se data extract karta hai
âĸ URL mein
âĸ Read aur Write dono kar sakte ho
âĸ Example:
Use Cases:
âĸ useParams: Resource identification (user ID, product ID)
âĸ useSearchParams: Filtering, sorting, pagination, search queries
Example:
âĸ
âĸ
useParams:
âĸ URL path segments se data extract karta hai
âĸ Route definition mein define hota hai:
/user/:idâĸ Read-only hai
âĸ Example:
/user/123 â { id: '123' }useSearchParams:
âĸ Query strings se data extract karta hai
âĸ URL mein
? ke baad aata haiâĸ Read aur Write dono kar sakte ho
âĸ Example:
/products?sort=price&category=electronicsUse Cases:
âĸ useParams: Resource identification (user ID, product ID)
âĸ useSearchParams: Filtering, sorting, pagination, search queries
Example:
/products/123?color=red&size=largeâĸ
useParams() â { productId: '123' }âĸ
useSearchParams() â { color: 'red', size: 'large' }
Hard
Q6: Nested routes mein Outlet component ka role explain karo. Index routes kya hote hain?
Answer:
Outlet Component:
âĸ Parent route component mein child routes render karne ke liye placeholder hai
âĸ Jaise HTML mein
âĸ Context pass kar sakta hai child routes ko
Index Routes:
âĸ Default child route jo parent route ke exact path pe render hota hai
âĸ
âĸ
âĸ
Outlet Component:
âĸ Parent route component mein child routes render karne ke liye placeholder hai
âĸ Jaise HTML mein
<slot> tag hota hai, waise hi kaam karta haiâĸ Context pass kar sakta hai child routes ko
function Dashboard() {
return (
<div>
<Sidebar />
<Outlet /> {/* Child routes yahan render honge */}
</div>
);
}Index Routes:
âĸ Default child route jo parent route ke exact path pe render hota hai
âĸ
index prop use karte hain, path nahi
<Route path="/dashboard" element={<Dashboard />}>
<Route index element={<Overview />} />
<Route path="settings" element={<Settings />} />
</Route>âĸ
/dashboard â Overview render hogaâĸ
/dashboard/settings â Settings render hoga
Hard
Q7: React Router v6 mein route ranking kaise kaam karti hai? Ambiguous routes ko kaise handle karta hai?
Answer: React Router v6 automatic route ranking system use karta hai jo best match find karta hai:
Ranking Priority (High to Low):
1. Static segments:
2. Dynamic segments:
3. Splat routes:
4. Index routes:
Example:
âĸ
âĸ
âĸ
V5 vs V6:
âĸ V5 mein order matter karta tha (first match wins)
âĸ V6 mein specificity matter karti hai (best match wins)
âĸ V6 mein
Ranking Priority (High to Low):
1. Static segments:
/about2. Dynamic segments:
/:id3. Splat routes:
/*4. Index routes:
indexExample:
<Routes>
<Route path="/users/new" element={<NewUser />} />
<Route path="/users/:id" element={<UserProfile />} />
<Route path="/users/*" element={<UsersLayout />} />
</Routes>âĸ
/users/new â NewUser (static match - highest priority)âĸ
/users/123 â UserProfile (dynamic match)âĸ
/users/anything/else â UsersLayout (splat match)V5 vs V6:
âĸ V5 mein order matter karta tha (first match wins)
âĸ V6 mein specificity matter karti hai (best match wins)
âĸ V6 mein
exact prop ki zaroorat nahi