Data loading with router loaders

Intermediate · 25 min

Route loader and action functions, useLoaderData, and how loading data before render avoids the useEffect loading-spinner waterfall.

Before thisNested routes and layoutsData fetching in effects

PedroTech · 51 min · from 26:18

Data loading with router loaders

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by PedroTechReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A route's `loader` function runs before that route's element renders, and React Router waits for it, so the component never has to render in a state where its data is still undefined.
  • `useLoaderData()` inside the route's component returns exactly what that route's `loader` returned — no `useEffect`, no `useState` for the fetched value, no separate loading flag to manage inside the component.
  • Fetching inside `useEffect` means the component mounts first, renders a loading state, fires the request, and re-renders again once data arrives — a render-then-fetch waterfall that `loader` fetches around by moving the request before the render.
  • An `action` function is a `loader`'s counterpart for writes: it runs in response to a form submission or a programmatic call and is the place mutations belong, instead of an event handler calling `fetch` directly.
  • Nested routes can each have their own `loader`, and React Router runs every matched route's loader in parallel rather than one after another, which is faster than each nested component fetching independently in its own effect.
  • Because the loader runs outside the component, it has no access to hooks — it receives a plain request/params object and returns plain data, which keeps data-loading logic testable independent of rendering.

The waterfall useEffect fetching creates

The data-fetching-in-effects lesson showed the standard pattern: a component mounts, useEffect fires a request, and until that request resolves the component renders some loading state.

function ProductDetail() {
  const { id } = useParams();
  const [product, setProduct] = useState(null);

  useEffect(() => {
    let cancelled = false;
    fetch(`/api/products/${id}`)
      .then((r) => r.json())
      .then((data) => { if (!cancelled) setProduct(data); });
    return () => { cancelled = true; };
  }, [id]);

  if (!product) return <Spinner />;
  return <h1>{product.name}</h1>;
}

This works, but notice the sequence: React has to render the component once with no data (to mount it and let the effect run), fire the request only after that render commits, and then re-render a second time once the response arrives. Nest a few of these — a layout that fetches the current user, a page that fetches a list, a detail panel that fetches one record — and each one can’t start fetching until its parent has mounted, so the requests fire one render-generation after another instead of all starting immediately. That staggered sequence is often called a fetch waterfall, and from the user’s side it looks like several spinners appearing and resolving in sequence rather than one.

Loading data before the route renders

React Router’s data APIs move the fetch earlier: instead of fetching from inside the component, you attach a loader function directly to the route, and the router runs it before rendering that route’s element.

import { createBrowserRouter, RouterProvider, useLoaderData } from "react-router-dom";

const router = createBrowserRouter([
  {
    path: "/products/:id",
    element: <ProductDetail />,
    loader: async ({ params }) => {
      const res = await fetch(`/api/products/${params.id}`);
      if (!res.ok) throw new Response("Not found", { status: 404 });
      return res.json();
    },
  },
]);

function ProductDetail() {
  const product = useLoaderData();
  return <h1>{product.name}</h1>;
}

The loader receives the matched route’s params (the same values useParams would return) and a request object, and whatever it returns becomes available to the component via useLoaderData(). React Router waits for the loader’s promise to resolve before it renders <ProductDetail /> at all, so by the time the component’s body runs, product is already real data — there is no null state to guard against inside the component, and no separate loading flag to thread through. The navigation that triggered this route change can show a pending UI at the router level while the loader runs, but the component itself never has to render in an incomplete state.

This is the core difference worth holding onto: useEffect fetches after a render, which is why a render-with-no-data has to exist; a loader fetches before a render, so that render never happens. For nested routes, this compounds further — React Router runs every matched route’s loaders in parallel rather than waiting for a parent’s loader before starting a child’s, which is strictly faster than each nested component firing its own effect only after its parent has mounted.

Writing data with action

loader covers reads. The parallel API for writes is action — a function that runs when a <Form> on that route is submitted (or when code calls the router’s submit function directly), rather than inside an onSubmit handler calling fetch itself:

{
  path: "/products/:id/edit",
  element: <EditProduct />,
  loader: async ({ params }) => fetch(`/api/products/${params.id}`).then((r) => r.json()),
  action: async ({ request, params }) => {
    const formData = await request.formData();
    await fetch(`/api/products/${params.id}`, {
      method: "PUT",
      body: formData,
    });
    return redirect(`/products/${params.id}`);
  },
}

Keeping the mutation as a route action rather than scattering fetch calls through event handlers means the same route that loads a record also owns how it’s updated, and the router can coordinate re-running the relevant loaders afterward so the UI reflects the write without you wiring that refresh by hand.

When useEffect fetching is still the right tool

None of this makes useEffect-based fetching obsolete. Loaders are tied to a route — they’re the right fit when a particular URL’s data should be ready before that URL’s page appears. Data that depends on something other than the route (a value typed into a search box, a websocket subscription, polling on an interval) still belongs in an effect, because it has no route transition to hang off of. The two lessons work together: routes own what you navigate to, effects own what happens while you’re already there.

What the video covers

This lesson picks up the data-loading chapter of the same PedroTech React Router v7 tutorial used in the two previous routing lessons — the segment covering loader functions and actions for mutation, in current v7 framework-mode syntax. The video is a solid, practical demonstration of wiring a loader to a route and reading it back, but it builds the comparison implicitly rather than naming it: it doesn’t explicitly walk through why this beats fetching inside useEffect, which is the contrast this lesson’s opening sections spend most of their time on, including the waterfall diagram in prose and the parallel-loader point for nested routes. Watch the video for the concrete “wire a loader into a real route” mechanics; use this lesson for the reasoning about why that wiring is worth doing over the pattern from the data-fetching-in-effects lesson.

Where this fits

This closes out the routing group. The next group in the roadmap moves from React Router’s own data loading to a dedicated data-fetching library — starting with the case for a data-fetching library, which covers problems loaders don’t solve, like caching a response across different routes and revalidating it in the background.

Check yourself

  1. 01What does a route's `loader` function do, and when does it run relative to that route's element?

    It runs before the route's element is rendered, typically to fetch the data that element needs; React Router waits for the loader's returned (or resolved) value before rendering, so the component can assume its data already exists.

  2. 02How does a component read the data its route's loader fetched?

    By calling `useLoaderData()` inside that route's component, which returns exactly whatever the matching route's `loader` function returned, with no local state or effect needed to hold it.

  3. 03Why does fetching inside `useEffect` typically show a loading spinner that a route `loader` can avoid?

    A `useEffect`-based fetch only starts after the component has already mounted and rendered once, so there is necessarily a render where the data isn't there yet — that's the loading state. A `loader` runs before the route renders at all, so by the time the component's first render happens, the data is already available and no spinner render is needed for that handoff.

  4. 04What is a route `action` for, and how does it differ from a `loader`?

    A `loader` is for reading data before a route renders; an `action` is its counterpart for writing data, running in response to a form submission or a programmatic submit call, and is where a mutation like creating or updating a record belongs instead of inside a click handler's own `fetch` call.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark