Route loaders and actions

Topic 3 of 3 in Routing7 min readIntermediateFree course

Overview

So far, components have fetched their own data after rendering. React Router’s data mode offers a different model, borrowed from how the web has always worked: each route declares a loader that gets its data before rendering, and an action that handles form submissions. The router coordinates everything — loading states, errors, revalidation — so your components stay simple.

Navigating to /courses/react: clicking a Link runs the route’s loader to fetch course data, then the component renders and reads it with useLoaderData. Submitting a Form with method post: the formData goes to the route’s action, which saves and may redirect, and then loaders revalidate so the UI shows fresh data. Data loads in parallel with the route code, before render.

Loaders

JSX
import { createBrowserRouter, useLoaderData } from 'react-router';

const router = createBrowserRouter([
  {
    path: '/courses/:slug',
    loader: async ({ params }) => {
      const res = await fetch(`/api/courses/${params.slug}`);
      if (res.status === 404) throw new Response('Not found', { status: 404 });
      if (!res.ok) throw new Error('Failed to load course');
      return res.json();
    },
    Component: CoursePage,
  },
]);

function CoursePage() {
  const course = useLoaderData();
  return <h1>{course.title}</h1>;
}

When the user clicks a link to /courses/react, the router:

  1. matches the routes for the new URL,
  2. calls every matching route’s loader in parallel (root layout, course layout, course page…),
  3. waits for them, then renders the new page with the data ready.

The component never deals with loading or “data might be undefined” states. A loader receives params, the request (with its URL and an abort signal), and returns any value — plain objects and arrays are fine.

Reading search params in a loader

JSX
loader: async ({ request }) => {
  const url = new URL(request.url);
  const q = url.searchParams.get('q') ?? '';
  return fetchJson(`/api/courses?q=${encodeURIComponent(q)}`, { signal: request.signal });
},

Passing request.signal lets the router abort the fetch if the user navigates elsewhere first.

Pending UI

While loaders run, the current page stays on screen. Show that something is happening with useNavigation:

JSX
import { useNavigation, Outlet } from 'react-router';

function RootLayout() {
  const navigation = useNavigation();
  const isNavigating = navigation.state !== 'idle';

  return (
    <>
      {isNavigating && <div className="progress-bar" aria-label="Loading" />}
      <main style={{ opacity: isNavigating ? 0.6 : 1 }}>
        <Outlet />
      </main>
    </>
  );
}

navigation.state is 'idle', 'loading' (running loaders) or 'submitting' (running an action).

Actions and Form

Actions handle data changes. React Router’s <Form> submits to the current route’s action — like an HTML form, but without a page reload:

JSX
import { Form, redirect, useActionData, useNavigation } from 'react-router';

const route = {
  path: '/courses/new',
  action: async ({ request }) => {
    const formData = await request.formData();
    const title = String(formData.get('title') ?? '').trim();

    if (title.length < 3) {
      return { errors: { title: 'Title must be at least 3 characters' } };
    }

    const course = await createCourse({ title });
    return redirect(`/courses/${course.slug}`);
  },
  Component: NewCourse,
};

function NewCourse() {
  const actionData = useActionData();
  const navigation = useNavigation();
  const submitting = navigation.state === 'submitting';

  return (
    <Form method="post">
      <label htmlFor="title">Title</label>
      <input id="title" name="title" />
      {actionData?.errors?.title && <p role="alert">{actionData.errors.title}</p>}
      <button type="submit" disabled={submitting}>
        {submitting ? 'Creating…' : 'Create course'}
      </button>
    </Form>
  );
}
  • <Form method="post"> serialises the fields and calls the route’s action with a request.
  • An action can return data (read with useActionData(), perfect for validation errors) or redirect somewhere.
  • After any action, the router revalidates: it re-runs the loaders on the page, so every part of the UI shows the updated data. No manual cache invalidation.

useFetcher: mutations without navigation

Not every change should navigate. Marking a lesson complete, toggling a favourite or rating a course should update data in place. useFetcher gives you a form (and loader access) that doesn’t change the URL:

JSX
import { useFetcher } from 'react-router';

function FavouriteButton({ course }) {
  const fetcher = useFetcher();
  // optimistic: show the value being submitted while it's in flight
  const favourite = fetcher.formData
    ? fetcher.formData.get('favourite') === 'true'
    : course.favourite;

  return (
    <fetcher.Form method="post" action={`/courses/${course.slug}/favourite`}>
      <button name="favourite" value={favourite ? 'false' : 'true'}>
        {favourite ? '★' : '☆'}
      </button>
    </fetcher.Form>
  );
}

Each fetcher has its own state (idle, submitting, loading) and data, so many can run at once — one per course card.

Errors

Throw from a loader or action — or let a component throw while rendering — and the router renders the nearest route ErrorBoundary instead of the route’s component:

JSX
import { isRouteErrorResponse, useRouteError } from 'react-router';

function CourseError() {
  const error = useRouteError();

  if (isRouteErrorResponse(error)) {
    // a thrown Response
    return <h1>{error.status === 404 ? 'Course not found' : `Error ${error.status}`}</h1>;
  }
  return <h1>Something went wrong</h1>;
}

const route = {
  path: '/courses/:slug',
  loader: courseLoader,
  Component: CoursePage,
  ErrorBoundary: CourseError,
};

Errors bubble up to the closest route with an ErrorBoundary, so the root layout’s boundary can catch everything while deeper routes handle their own errors and keep the surrounding layout on screen.

Redirects and auth in loaders

Loaders are the ideal place for authentication checks — they run before anything renders:

JSX
async function requireUser() {
  const user = await getCurrentUser();
  if (!user) throw redirect('/login');
  return user;
}

{
  path: 'dashboard',
  loader: async () => {
    const user = await requireUser();
    return fetchJson(`/api/users/${user.id}/dashboard`);
  },
  Component: Dashboard,
}

Loaders and TanStack Query together

Loaders decide when to fetch (on navigation, in parallel); TanStack Query handles caching. Combining them gives you the best of both: the loader primes the cache, and components read from it:

JSX
loader: ({ params }) => queryClient.ensureQueryData(courseQueries.detail(params.slug)),

function CoursePage() {
  const { slug } = useParams();
  const { data: course } = useSuspenseQuery(courseQueries.detail(slug));
}

The web’s model, upgraded: forms post to actions, links load pages, and the data is fresh after every change. React Router adds instant client-side transitions, pending UI and parallel loading on top.

Exercise

Load and update a course

Create a /courses/:slug route whose loader calls getCourse(params.slug) (provided) and throws a 404 Response if it returns null. The component shows the title with useLoaderData() and a <Form method="post"> with a title input to rename it. The route’s action validates the title (at least 3 characters — return { error } otherwise), calls updateCourse(slug, title) and returns { ok: true }. Show the error with useActionData(), a “Saving…” button label with useNavigation(), and an ErrorBoundary that shows “Course not found” for 404s.

JavaScript
import { Form, isRouteErrorResponse, useActionData, useLoaderData, useNavigation, useRouteError } from 'react-router';

// provided: getCourse(slug), updateCourse(slug, title)

export const courseRoute = {
  path: '/courses/:slug',
  // your code here
};

Summary

  • A route loader fetches data before the route renders; the component reads it with useLoaderData().
  • Loaders for all matching routes run in parallel, avoiding fetch waterfalls.
  • A route action handles <Form method="post"> submissions; after it runs, loaders revalidate automatically.
  • useNavigation() exposes loading and submitting states for pending UI; useFetcher() submits without navigating.
  • Throw redirect() or a Response from loaders and actions; render errors with a route ErrorBoundary.