🔥 7 React Router Tips Every Developer Should Know (With Real Examples)

YashikaYashika
5 min read

💡 Tired of just using <Route> and <Link>? Let’s unlock the hidden superpowers of React Router DOM and level up your React apps.

React Router DOM is the backbone of routing in most React projects. It handles navigation, URL management, route rendering, and so much more. But here’s the truth:

👉 Most developers only scratch the surface.

In this post, I’ll share 7 game-changing React Router tips that go beyond the basics with real project use cases for each. Whether you're building a dashboard, e-commerce app, or portfolio, these tips will help you write smarter, cleaner, and more scalable code.


📦 1. Lazy Load Route Components with React.lazy()

Why load every route upfront when some pages are rarely visited?

// Lazily load pages to split the bundle and improve performance
const OrderHistory = lazy(() => import("./pages/OrderHistory"));
const ProductDetail = lazy(() => import("./pages/ProductDetail"));

Wrap your routes with <Suspense>:

// Wrap Routes in <Suspense> to handle the loading state gracefully
<Suspense fallback={<div>Loading...</div>}>
  <Routes>
    {/* Loads this component only when /orders is visited */}    
    <Route path="/orders" element={<OrderHistory />} />
    {/* Dynamic route for product details using URL parameter */}
    <Route path="/product/:id" element={<ProductDetail />} />
  </Routes>
</Suspense>

Real Use Case: In an e-commerce app, lazy-load "Order History" or "Product Detail" pages to reduce initial bundle size.


🧭 2. Use useLocation() to Control Layout Visibility

Sometimes you want to hide the navbar/footer on certain pages like modals or full-screen views.

import { useLocation } from "react-router-dom";

// Hook to access the current location object
const location = useLocation();
// Detect if the current route starts with /project/
const isMinimalView = location.pathname.startsWith("/project/");

return (
  <>
    {/* Conditionally render Navbar and Footer */}
    {!isMinimalView && <Navbar />}
    <Outlet /> {/* Placeholder for nested routes */}
    {!isMinimalView && <Footer />}
  </>
);

Real Use Case: On a portfolio site, hide layout on /project/:id to focus on the project preview.


🧩 3. Create Reusable Layouts with Nested Routing + <Outlet />

For dashboards or admin panels, nested routes keep your code DRY and modular.

// Main routing file
<Route path="/admin" element={<AdminLayout />}>
  {/* Child routes rendered inside <Outlet /> in AdminLayout */}
  <Route path="users" element={<UserList />} />
  <Route path="settings" element={<Settings />} />
</Route>
//AdminLayout.jsx
import { Outlet } from "react-router-dom";

const AdminLayout = () => (
  <div className="admin">
    <Sidebar /> {/* Static sidebar remains across routes */}
    <main>
       <Outlet /> {/* Content changes based on child route */}
    </main>
  </div>
);

Real Use Case: Keep your sidebar persistent while the main content changes dynamically.


🔐 4. Protect Routes Using <Navigate />

Protect routes like /apply or /checkout for logged-in users.

// Simulate login check (replace with your auth logic)
const isLoggedIn = true;
<Route
  path="/apply"
  // Redirect to login page if not authenticated
  element={isLoggedIn ? <ApplyForm /> : <Navigate to="/login" replace />}
/>

Real Use Case: In a job portal, only logged-in users should access the application form.


🔄 5. Scroll to Top on Route Change (Fix That Annoying Scroll Bug)

React Router doesn’t auto-scroll to the top when navigating pages. Here’s a reusable fix:

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

// Scrolls to the top whenever the route changes
const ScrollToTop = () => {
  const { pathname } = useLocation();
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]); // Re-run effect on route change
  return null; // No UI element needed
};

Use it globally:

<BrowserRouter>
  <ScrollToTop />
  <Routes>{/* your routes */}</Routes>
</BrowserRouter>

Real Use Case: Blogs, long product pages, or tutorials.


🌐 6. Use useParams() for Dynamic Routing

Get clean, SEO-friendly URLs like /product/:id or /blog/:slug.

<Route path="/product/:id" element={<ProductPage />} />
//ProductPage.jsx
const { id } = useParams(); // Extract product ID from URL
const [product, setProduct] = useState(null);

useEffect(() => {
  // Fetch product data based on the route parameter
  fetch(`/api/products/${id}`)
    .then(res => res.json())
    .then(setProduct);
}, [id]);

Real Use Case: Perfect for e-commerce, blog, or course platforms.


📬 7. Pass Navigation State with navigate(..., { state })

Instead of stuffing query parameters into the URL, pass state data cleanly.

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

const navigate = useNavigate();

// On successful form submission
const handleSubmit = () => {
  navigate("/thankyou", {
    state: {
      orderId: "ORD12345",
      totalAmount: "$49.99",
    },
  });
};

In the target component:

// ThankYou.jsx
import { useLocation } from "react-router-dom";

const ThankYou = () => {
  const { state } = useLocation(); // Get passed state

  return (
    <div>
      <h1>Thank You!</h1>
      <p>Order ID: {state?.orderId}</p>
      <p>Total Amount: {state?.totalAmount}</p>
    </div>
  );
};

Real Use Case: Thank you pages, flash messages, or OTP pages.


✨ Bonus: Use a Central Config for Routes

Clean up your Routes by mapping them from a config file:

// routes/config.js
import Home from "../pages/Home";
import About from "../pages/About";

const routes = [
  { path: "/", element: <Home /> },
  { path: "/about", element: <About /> },
];

export default routes;
// App.jsx
import routes from "./routes/config";

<Routes>
  {routes.map(({ path, element }) => (
    <Route key={path} path={path} element={element} />
  ))}
</Routes>

✅ Easier to scale and modify when your app grows.


🧠 Final Thoughts

React Router DOM is more than just a routing library it’s a toolbox full of superpowers that most developers overlook.

Here’s what you should remember:

  • Lazy load routes to boost speed ⚡

  • Use useLocation() for layout control 🧩

  • Protect and redirect routes securely 🔐

  • Pass data with state, not just query strings 💌

  • Improve UX with scroll-to-top behavior 👆

Start using even 2–3 of these tips and your app will feel snappier, smarter, and more scalable.


🙌 Like this post?

If you enjoyed this, follow me for more React/JS tips, or drop a 💬 comment telling me your favorite React Router trick!


✍️ Written by Yashika Salonia

React dev | UI/UX enthusiast | Building real projects from real problems

0
Subscribe to my newsletter

Read articles from Yashika directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yashika
Yashika