SkillPilotAI

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).
React (JSX)
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>  );}
Output
-- / --URL: /# Home -- /orders (logged out) --URL: /ordersUser: logged out# My Orders

44.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.
React (JSX)
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>  );}
React (JSX)
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 />;}
Output
-- logged out: redirected --URL: /login# Login -- logged in as Riya --URL: /ordersUser: Riya# My Orders
Protected route decision
  1. 1.User opens /orders

  2. 2.Router matches the ProtectedRoute layout route

  3. 3.useAuth() gives the current user

  4. 4.No user: <Navigate to="/login" replace />

  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.
React (JSX)
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>  );}
Output
-- initial --URL: /products[button] Sort: popular, Page: 1 -- after clicking the button --URL: /products?sort=price&page=1[button] Sort: price, Page: 1
Why filters belong in the URL
  1. 1.Sort kept in useState: lives only in memory

  2. 2.Refresh or shared link = fresh page load

  3. 3.State lost, back to default

  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.
React (JSX)
// URL: /products?sort=price&page=1function nextPage() {  setParams({ page: "2" });}
Output
-- before click --URL: /products?sort=price&page=1 -- after nextPage() --URL: /products?page=2

44.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.
React (JSX)
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>;}
Output
URL: /orders/1042# 1042: Shipped

44.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").
React (JSX)
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>.
React (JSX)
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} />;}
The data mode flow
  1. 1.User clicks a Link or submits a Form

  2. 2.Router runs the loader (read) or action (write)

  3. 3.After an action, loaders run again (revalidate)

  4. 4.Component renders with fresh data via useLoaderData

Loaders remove the useEffect fetch waterfall

44.8 Comparison: useEffect fetch vs loader

PointuseEffect fetchLoader (data mode)
When data loadsAfter the component rendersBefore the route renders
Loading stateManual useState + spinnerNot needed in the component
Nested routesWaterfall: child waits for parentLoaders of matched routes run in parallel
After a changeRefetch by handLoaders revalidate after an action
Router setupAny routercreateBrowserRouter + 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.
React (JSX)
const page = params.get("page") ?? "1"; function nextPage() {  setParams({ page: page + 1 });}
React (JSX)
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.