Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 50 ยท Projects

Project: A Blog with Loaders and Search Params

Build a blog with a post list, post pages, tag filters, search and pagination stored in the URL, loader-style data fetching, pending UI and nested error boundaries.

A blog looks simple, but it contains the two things that make real routing interesting: data that depends on the URL and state that should live in the URL. The post page needs a post, and the post is chosen by the path. The list page needs a page number, a tag and a search term, and users expect that sharing the address, pressing Reload or going Back all keep those choices.

In this project you will build both screens. You will write the data code first, as plain functions that you can run and read without any React, then add the router and the user interface. Along the way you will use loaders, search params, state in the URL, pending UI and error boundaries. As in the other projects, the real library cannot be installed in the live editor. The runnable code uses a hand-written stand-in router with the same shape (route objects, loader, errorElement, Outlet, useLoaderData, useNavigation), and every step shows the real React Router code as read-only. Where the stand-in differs from the real router, the text says so.

The plan

flowchart LR
    A["URL change<br/>/posts?tag=css&page=2"] --> B["match routes"]
    B --> C["run loaders in parallel"]
    C -->|"success"| D["render with loader data"]
    C -->|"throws"| E["render nearest errorElement"]
    D --> F["user clicks a filter link"]
    F --> A

The URL is the only input. Filters are links, and every click is a navigation that runs the loaders again.

Three design rules shape the code:

  1. The URL is the source of truth. The list does not keep tag, page or q in useState. It reads them from the loader's result, and changing a filter means navigating to a new URL.
  2. Loaders validate. A hand-edited URL such as ?page=abc or ?page=99 must not crash the page. The loader clamps and defaults.
  3. Each failure has an owner. A missing post is an expected condition of the post route, so that route has its own error element, while the layout keeps the header on screen.

Step 1: the loader as a plain function

A loader receives the route params and the request. In the real router, request is a Web Request and you read the query string with new URL(request.url).searchParams. In our stand-in, request.searchParams is handed over ready-made, and in the first example we skip even that and pass a URLSearchParams directly, so we can test the logic by itself.

The loader does five things: it reads and defaults the parameters, loads the posts, filters them, works out the page count and returns a plain object holding everything the screen needs, including the clamped page number.

This is a console example (a js TryIt): press Run and read the output.

JS Step 1: the posts loader, tested on its own

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output line by line. The empty query returns the first three of eight posts on page 1 of 3. ?page=2 returns the next three. ?page=99 is clamped to page 3, the last one, and ?page=abc falls back to page 1, because Number("abc") is NaN and NaN || 1 is 1. Filters combine: ?tag=css&q=grid finds the single post that has the tag and the word. A tag that does not exist yields an empty list with page 1/1, which the screen will explain with a friendly message instead of crashing.

Here is the same loader as real React Router code. The only differences are the request handling and the way the data is fetched:

JSX
// routes/posts.jsx - React Router (read-only)
export async function postsLoader({ request }) {
  const url = new URL(request.url);
  const tag = url.searchParams.get("tag") ?? "";
  const q = (url.searchParams.get("q") ?? "").trim().toLowerCase();
  const wanted = Math.max(1, Number(url.searchParams.get("page")) || 1);

  const response = await fetch("/api/posts", { signal: request.signal });
  if (!response.ok) {
    throw new Response("Could not load posts", { status: 502 });
  }
  const all = await response.json();
  // ... same filtering and paging as above ...
  return { tag, q, page, pages, total: matching.length, items };
}

Passing request.signal to fetch lets the router cancel a request when the user clicks something else before it finishes.

Step 2: the post page and its errors

The post loader is shorter, but its failure path matters. When the slug does not exist, it throws instead of returning null. A thrown value is handled by the nearest errorElement, and the page component then never has to check for a missing post: if it renders, it has data. In the real library you would write:

JSX
// routes/post.jsx - React Router (read-only)
import { data } from "react-router";

export async function postLoader({ params, request }) {
  const response = await fetch("/api/posts/" + encodeURIComponent(params.slug), {
    signal: request.signal,
  });
  if (response.status === 404) {
    throw data("There is no post called " + params.slug, { status: 404 });
  }
  return response.json();
}

// in the route config
{ path: "posts/:slug", Component: PostPage, loader: postLoader, ErrorBoundary: PostError }

and PostError reads the thrown value with useRouteError() and tests it with isRouteErrorResponse(error). The stand-in throws a plain object { status, message } and gives it the same hook name.

Step 3: the whole blog

Now the router and the screens. Notice four things as you read:

  • Routes re-runs all loaders of the matched routes in parallel whenever the hash (path or query) changes. It keeps showing the old screen until the new data arrives and reports navigation.state === "loading" meanwhile, which is also how the real router behaves.
  • A stale response must not win. When you click quickly, an older request may finish after a newer one. The current flag in the effect's cleanup drops outdated results. The real router cancels and ignores superseded navigations for you.
  • The tag chips, the page links and the search form never set React state. They are plain links with computed addresses (listHref), or, for the form, a navigation. listHref keeps the other filters and resets page to 1 when you change the tag or the search term, as users expect. The real code does the same with <Link to="?tag=css">, with a search-only target.
  • If a loader throws, the stand-in looks upward from the failing route for the nearest errorElement and renders it in place of that route. The layout above it stays.
Step 3: the blog with loaders, filters and pagination

Use the blog like a visitor would, and watch the address bar:

  • Open the page. The empty path redirects to /posts and the first three posts appear after a short pause. While data loads, the old screen stays dimmed and the header shows "Loading...". That is the pending UI in a few lines, driven entirely by useNavigation.
  • Click the css tag. The address becomes #/posts?tag=css, two posts show, and the css chip is bold. Then click Next on the unfiltered list, copy the address and paste it into a new tab: the same page opens. That is the practical benefit of URL state.
  • Search for react. The form never touches state: it computes a link and navigates. Clear the input, submit again and the q parameter disappears from the address.
  • Edit the address by hand to #/posts?page=99. You land on the last page, because the loader clamps. Try #/posts?tag=nope for the empty-state message.
  • Open a post, then use the css tag link on its page. Links are the primary interface: a tag on a post is just /posts?tag=css.
  • Open #/posts/does-not-exist. The post route's errorElement renders in place of the post, with the header still visible. A deeper boundary beats a shallower one, which is why the layout's generic "Something went wrong" does not appear.

Why filters belong in the URL

Compare with the usual React approach, where tag, q and page live in useState inside the list component. Reload resets them, Back leaves the page instead of undoing the last filter, and nobody can share "CSS posts, page 2". Putting them in the URL fixes all three, removes the duplicated state (the URL and a state copy can no longer disagree) and gives the loader a single, complete description of what to fetch. The cost is that every change is a navigation, so very frequent changes (typing in a search box) should be debounced or committed on submit, as here, and filter changes usually use replace so that the history is not filled with every keystroke. More patterns are in Putting UI State in the URL.

Extend the project

  1. Add a sort=oldest search param and a link to toggle it.
  2. Show "Showing 4-6 of 8" using the values the loader already returns.
  3. Prefetch the next page when the user hovers over Next. Compare with the real router's prefetch prop on Link in framework mode.
  4. Turn the search form into a real <Form method="get">. What does the router do with it (Actions and Form)?
  5. Add a lazy import for the post page (Lazy Routes).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A visitor opens /posts?page=abc. Where should this be handled?

    Search params are user input. The loader validates them, so the component can assume a valid page, tag and query. Number('abc') is NaN, which the loader replaces with page 1.
  2. 2. Why does the list read tag and page from the loader data instead of keeping them in useState?

    When filters are in the URL, any copy of the address shows the same results, Back undoes a filter change, and there is no second copy of the state that could disagree.
  3. 3. The post loader throws for an unknown slug, and both the layout and the post route have an error element. Which one renders?

    Errors bubble up to the nearest error element. The post route has its own, so only that part of the screen is replaced and the layout stays.
  4. 4. What does navigation.state === 'loading' tell you in this project?

    The router keeps the old screen visible while the next loaders run and reports 'loading' during that time, which is perfect for dimming content and showing a progress hint.
  5. 5. A user clicks 'css', then 'react' quickly, and the css response arrives last. What prevents the screen from showing css results under the react address?

    Responses can arrive in any order. Ignoring results from superseded navigations keeps the screen consistent with the URL.

Summary

  • Treat the URL as the input of a screen: path params choose the record, search params hold filters, sorting and page.
  • A loader is a plain async function of { params, request } that validates input, loads data and returns everything the screen needs.
  • Filters, tags and pagination are ordinary links to computed addresses, so they are shareable, bookmarkable and Back-friendly.
  • navigation.state gives you pending UI for free while the previous screen stays visible.
  • Throw from loaders for expected failures and give the route an errorElement, so the nearest boundary replaces only the affected part of the screen.

Next: Project: An Admin Dashboard with Protected Routes