Skip to main content

Command Palette

Search for a command to run...

๐Ÿ”ฅ 7 React Router Tips Every Developer Should Know (With Real Examples)

Go beyond basic routing and take your React apps to the next level with these underrated features of React Router DOM.

Updated
โ€ข5 min read
๐Ÿ”ฅ 7 React Router Tips Every Developer Should Know (With Real Examples)

๐Ÿ’ก 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