Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 50 ยท Practice and Review

React Router Cheat Sheet

A one-page React Router v7 cheat sheet: route patterns, components, hooks, loader and action APIs, data router config and framework mode files, with runnable stand-in demos.

This is the page to keep open in a tab while you work. It does not replace the lessons; every section links to the lesson that explains the idea in full. The tables list the real React Router v7 API. The two live demos use a small hand-written stand-in built from React, because the sandbox cannot install react-router, and each says exactly what it imitates.

Install and imports

Terminal
npm install react-router
What Import
Components, hooks, createBrowserRouter, redirect, data import { ... } from 'react-router'
RouterProvider for the browser (data mode) import { RouterProvider } from 'react-router/dom'
Old package name (v6 and earlier code) react-router-dom, now only re-exports react-router

See Installing and Your First Routes and Choosing Between Declarative, Data and Framework Mode.

The three modes

Mode Entry point You get
Declarative <BrowserRouter> + <Routes> + <Route> matching, links, hooks, navigation
Data createBrowserRouter(routes) + <RouterProvider> adds loader, action, <Form>, fetchers, pending state, error elements, lazy
Framework Vite plugin + app/routes.ts + route modules adds SSR, prerendering, generated types, server loaders, meta and links exports

Route patterns

Pattern Matches Params
/about exactly /about none
/users/:id /users/42 { id: '42' }
/:lang?/docs /docs and /en/docs { lang: 'en' } or {}
/files/* /files/a/b.txt { '*': 'a/b.txt' }
* anything not matched elsewhere { '*': '...' }
index (instead of path) the parent's exact URL none
no path (layout route) adds a wrapper, no URL segment none

Rules to remember: matches are ranked by specificity (static beats dynamic beats splat), not by order; trailing slashes are ignored; matching is case-insensitive unless the route has caseSensitive; params are always strings. See Routes and Matching and Dynamic Segments and useParams.

Pattern syntax: params, optional segments and splats

For /en/docs the optional pattern gives {"lang":"en"}, and for /docs it gives {}. The /files/* column returns {"*":"a/b.txt"} for the file path. The extra row /ABOUT/ matches /about with {}, which shows case-insensitive matching and ignored trailing slashes.

Components

Component Purpose
<BrowserRouter>, <HashRouter>, <MemoryRouter> declarative-mode routers (History API, hash, in memory for tests)
<Routes> / <Route path element> declare the route tree (the best match renders)
<Outlet context> where a child route renders inside its parent
<Link to replace state relative> navigate without a page load
<NavLink to end> a Link with isActive, isPending and aria-current="page"
<Navigate to replace state /> redirect when rendered
<Form method action> submit to a route action through the router
<ScrollRestoration /> restore scroll position on navigation
<Await resolve errorElement> render a promise returned by a loader (inside Suspense)
<RouterProvider router /> mount a data router (from react-router/dom)

See Link and NavLink, Redirects with Navigate and Nested Routes and Outlet.

JSX
// Real React Router v7 (declarative mode), read-only
import { BrowserRouter, Routes, Route, Outlet, NavLink } from 'react-router';

function Layout() {
  return (
    <>
      <nav>
        <NavLink to="/" end>Home</NavLink>
        <NavLink to="/blog">Blog</NavLink>
      </nav>
      <Outlet />
    </>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="blog" element={<BlogList />} />
          <Route path="blog/:slug" element={<BlogPost />} />
          <Route path="*" element={<NotFound />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

Hooks

Hook Returns Use it for
useParams() object of strings dynamic segments and the splat
useSearchParams() [URLSearchParams, setSearchParams] filters, sort, page, tabs
useLocation() { pathname, search, hash, state, key } current URL and navigation state
useNavigate() navigate(to | delta, options) imperative navigation in handlers
useMatch(pattern) match or null is this pattern active?
useMatches() array of matches with handle and data breadcrumbs, per-route metadata
useOutletContext() the context of the parent <Outlet> small shared values for children
useRoutes(config) rendered element route objects in declarative mode
useBlocker(when) blocker with state, proceed(), reset() unsaved changes (data routers)
useLoaderData() the route's loader result read page data
useRouteLoaderData(id) another route's loader result read a parent's data
useActionData() the route's last action result form validation errors
useNavigation() { state, location, formData, ... } global pending UI
useFetcher() fetcher with Form, load, submit, state, data mutations without navigating
useRevalidator() { revalidate, state } manual refresh of loaders
useRouteError() the thrown value inside an error element
useAsyncValue() resolved value inside <Await>

useNavigate options: { replace, state, relative }. navigate(-1) goes back one entry; navigate('..') goes up one route level. See useNavigate, useLocation and Navigation State and Search Params.

Loaders, actions and friends

JSX
// Real React Router v7 (data mode), read-only
import { createBrowserRouter, redirect, data } from 'react-router';

const router = createBrowserRouter([
  {
    path: '/',
    Component: Root,
    ErrorBoundary: RootError,
    children: [
      {
        path: 'posts/:postId',
        Component: Post,
        loader: async ({ params, request }) => {
          const url = new URL(request.url);
          const lang = url.searchParams.get('lang') ?? 'en';
          const post = await getPost(params.postId, lang);
          if (!post) {
            throw data('Not found', { status: 404 });
          }
          return post;
        },
        action: async ({ request, params }) => {
          const form = await request.formData();
          const error = validate(form);
          if (error) {
            return { error };
          }
          await savePost(params.postId, form);
          return redirect('/posts');
        },
        shouldRevalidate: ({ defaultShouldRevalidate }) => defaultShouldRevalidate,
        handle: { crumb: 'Post' },
      },
      { path: 'reports', lazy: () => import('./routes/reports') },
    ],
  },
]);
API Notes
loader({ request, params }) runs before render, in parallel for all matched routes; return data or a Response; throw to reach an error element
action({ request, params }) handles non-GET submits (request.formData()); after it finishes, loaders revalidate
redirect(url) return or throw from a loader or action; replace(url) replaces the history entry
data(body, { status }) return or throw data with a status (use it instead of the older json() helper)
shouldRevalidate decide whether this route's loader reruns after a navigation or action
lazy import a route's loader, action and Component on demand
errorElement / ErrorBoundary rendered when this route or a descendant throws
handle any value you attach to a route; read with useMatches()
isRouteErrorResponse(error) true for a thrown Response or data(...) (has status, statusText, data)

useNavigation().state moves through idle, submitting (an action is running), loading (loaders are running) and back to idle. fetcher.state uses the same three values. See Loaders, Actions and Form, useFetcher, Revalidation and Caching and Error Boundaries and Error Elements.

A NavLink is active when the URL equals its to or continues below it (/blog is active at /blog/hello). With end it is active only on an exact match, which is why the link to / needs it. The demo implements that rule and shows which links would be active for each URL. It is a stand-in for the real component; the real one also reports isPending and sets aria-current.

When is a NavLink active?

At /blog/hello the first link (to="/" without end) and the plain /blog link are both active, while to="/" end and to="/blog" end are not. At / only the two links to / are active.

Framework mode files

File Purpose
react-router.config.ts ssr, prerender, appDirectory, build options
app/routes.ts route config: route(path, file), index(file), layout(file, children), prefix(path, children)
app/root.tsx root layout, <Links />, <Meta />, <Scripts />, <ScrollRestoration />, root error boundary
app/routes/*.tsx route modules exporting default, loader, action, clientLoader, ErrorBoundary, meta, links, headers

loader and action run on the server; clientLoader and clientAction run in the browser. See Framework Mode Overview, Route Config and File Routes and Server Loaders, Client Loaders and Actions.

Quick answers

Question Answer
Links lose app state you used <a href>; use <Link>
Child never shows the parent is missing <Outlet />
Nested link goes to the wrong place relative links resolve per route; use relative="path" or an absolute path
Redirect loop the guard redirects to a page that is also behind the guard, or a missing replace
Deep links give 404 on the server serve index.html for unknown paths or use a hash router
Hook throws about a missing router the component is rendered outside a router; wrap it (tests included)
Data is stale after a mutation use an action, or call revalidate()

See Common Mistakes and Debugging, Migrating From v5, v6 and Remix and React Router Interview Questions. New to the React side? The React cheat sheet covers components, state and hooks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which object does useSearchParams return?

    useSearchParams returns [searchParams, setSearchParams], similar to useState. searchParams is a standard URLSearchParams.
  2. 2. What does <NavLink to="/"> without the end prop do on the URL /blog/hello?

    Without end, a NavLink is active for its own URL and anything below it. That is why root links usually need end.
  3. 3. A loader needs to show a not-found page. What is the idiomatic way?

    Throwing a response reaches the nearest error element, where isRouteErrorResponse exposes the status.
  4. 4. What are the values of useNavigation().state during a form submit with an action?

    The state is submitting while the action runs, then loading while loaders revalidate, then back to idle.

Summary

  • Keep the three modes in mind: declarative for matching and links, data mode for loaders, actions and pending state, framework mode for SSR and file-based tooling.
  • Patterns: :param, :param?, *, index and pathless layout routes; the best match wins by specificity.
  • Hooks read the URL (useParams, useSearchParams, useLocation), move you (useNavigate), and read router data (useLoaderData, useNavigation, useFetcher, useRouteError).
  • Loaders read, actions write and trigger revalidation, redirect and thrown responses control the flow, and lazy splits code per route.
  • Guards are for experience; the server enforces security.

You have reached the end of the React Router tutorial. Rework the exercises or build the shop project to make these tables second nature.