React Router advanced
Advanced React Router covers three real-app needs: protecting pages behind login, keeping shareable state like sort and page in the URL, and data mode, where loaders fetch data before a route renders and actions handle form submits.
44.1 Why is it used?
- Without a guard, a logged out user can type /orders in the address bar and the whole My Orders page opens.
- Filters kept in useState vanish on refresh or when the link is shared.
- Fetching in useEffect renders an empty page first and nested routes fetch one after another (waterfall).
import { Routes, Route } from "react-router";import { Home, Login, Orders } from "./pages"; export default function App() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<Login />} /> <Route path="/orders" element={<Orders />} /> </Routes> );}-- / --URL: /# Home -- /orders (logged out) --URL: /ordersUser: logged out# My Orders44.2 Protected route as a layout route
- ProtectedRoute is a gatekeeper used as a layout route with no path of its own.
- Every route nested inside it (like /orders) runs the check first.
- No user: return <Navigate to="/login" replace />. Logged in: return <Outlet /> to render the child page.
- replace swaps the history entry, so the back button does not trap the user in the same redirect.
import { Routes, Route } from "react-router";import { Home, Login, Orders } from "./pages";import ProtectedRoute from "./ProtectedRoute"; export default function App() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<Login />} /> <Route element={<ProtectedRoute />}> <Route path="/orders" element={<Orders />} /> </Route> </Routes> );}import { Navigate, Outlet } from "react-router";import { useAuth } from "./AuthContext"; export default function ProtectedRoute() { const { user } = useAuth(); if (!user) { return <Navigate to="/login" replace />; } return <Outlet />;}-- logged out: redirected --URL: /login# Login -- logged in as Riya --URL: /ordersUser: Riya# My Orders- Step 1
1.User opens /orders
- Step 2
2.Router matches the ProtectedRoute layout route
- Step 3
3.useAuth() gives the current user
- Step 4
4.No user: <Navigate to="/login" replace />
- Step 5
5.User present: <Outlet /> renders Orders
Frontend check only for UX; the server must still check the token
44.3 URL state: useSearchParams
- Sort, filter and page should survive refresh and sharing, so their home is the URL.
- useSearchParams looks like useState: [params, setParams].
- Read with params.get("sort") ?? "popular"; write with setParams({ sort: "price", page: "1" }).
- The URL updates and the screen re-renders automatically.
import { useSearchParams } from "react-router"; export default function Products() { const [params, setParams] = useSearchParams(); const sort = params.get("sort") ?? "popular"; const page = Number(params.get("page") ?? 1); function sortByPrice() { setParams({ sort: "price", page: "1" }); } return ( <button onClick={sortByPrice}> Sort: {sort}, Page: {page} </button> );}-- initial --URL: /products[button] Sort: popular, Page: 1 -- after clicking the button --URL: /products?sort=price&page=1[button] Sort: price, Page: 1- Step 1
1.Sort kept in useState: lives only in memory
- Step 2
2.Refresh or shared link = fresh page load
- Step 3
3.State lost, back to default
- Step 4
4.Sort in ?sort=price&page=1 survives refresh and sharing
44.4 Checkpoint: setParams replaces
- URL is ?sort=price&page=1 and nextPage calls setParams({ page: "2" }).
- Result: ?page=2. Passing an object replaces the whole query string; it does not merge.
// URL: /products?sort=price&page=1function nextPage() { setParams({ page: "2" });}-- before click --URL: /products?sort=price&page=1 -- after nextPage() --URL: /products?page=244.5 Loader and useLoaderData
- A loader is an async function the router calls with the URL params before rendering the route.
- useLoaderData() returns what the loader returned: no useEffect, no loading state in the component.
- The page opens with data ready.
import { useLoaderData } from "react-router"; export async function orderLoader({ params }) { const url = `/api/orders/${params.id}`; const res = await fetch(url); return res.json();} export default function Order() { const order = useLoaderData(); return <h1>{order.id}: {order.status}</h1>;}URL: /orders/1042# 1042: Shipped44.6 Action and Form
- For changing data (e.g. saving an address) data mode uses an action.
- <Form method="post"> from react-router submits without a page reload and calls the route's action.
- The action reads request.formData(), saves, and can return redirect("/checkout").
import { Form, redirect } from "react-router";import { saveAddress } from "./api";export async function addressAction({ request }) { const form = await request.formData(); await saveAddress(form.get("city")); return redirect("/checkout");} export default function Address() { return ( <Form method="post"> <input name="city" /> <button>Save</button> </Form> );}44.7 The data mode router
- createBrowserRouter takes an array of route objects with Component, loader and action.
- RouterProvider (from react-router/dom) gives the router to the app.
- loader, action and Form only work in data mode, not with plain <BrowserRouter>.
import { createBrowserRouter } from "react-router";import { RouterProvider } from "react-router/dom";import Order, { orderLoader } from "./Order";import Address, { addressAction } from "./Address"; const router = createBrowserRouter([ { path: "/orders/:id", Component: Order, loader: orderLoader }, { path: "/address", Component: Address, action: addressAction },]); export default function App() { return <RouterProvider router={router} />;}- Step 1
1.User clicks a Link or submits a Form
- Step 2
2.Router runs the loader (read) or action (write)
- Step 3
3.After an action, loaders run again (revalidate)
- Step 4
4.Component renders with fresh data via useLoaderData
Loaders remove the useEffect fetch waterfall
44.8 Comparison: useEffect fetch vs loader
| Point | useEffect fetch | Loader (data mode) |
|---|---|---|
| When data loads | After the component renders | Before the route renders |
| Loading state | Manual useState + spinner | Not needed in the component |
| Nested routes | Waterfall: child waits for parent | Loaders of matched routes run in parallel |
| After a change | Refetch by hand | Loaders revalidate after an action |
| Router setup | Any router | createBrowserRouter + RouterProvider |
44.9 Common mistakes
- Search params are always strings: page + 1 gives "11". Use Number() and update with a callback so other params like sort stay.
- Forgetting replace on Navigate, so Back keeps bouncing to the redirect.
- Myth: a protected route makes the app secure. It runs in the browser and can be bypassed with DevTools or a direct API call; real security is a server side token check on every API request.
const page = params.get("page") ?? "1"; function nextPage() { setParams({ page: page + 1 });}const page = Number(params.get("page") ?? 1); function nextPage() { setParams((prev) => { prev.set("page", String(page + 1)); return prev; });}44.10 Practical rules
- Keep the auth check in one layout route and use Navigate with replace.
- Shareable state (sort, filter, page) goes in the URL.
- Convert search params from strings.
- In data mode: loader to read, action to write.
44.11 Interview tips
- Protected route: a layout route that checks auth, returns <Navigate to="/login" replace /> without a user, otherwise <Outlet />.
- Always add: this is UX only, real authorization happens on the server.
- useSearchParams keeps shareable UI state in the URL; values are strings and setParams with an object replaces the query.
- Loaders fetch before render (no useEffect waterfall); actions handle Form submits and trigger revalidation.