0Pricing
React Academy · Lesson

Loaders & Actions (Data Router API)

Fetch route data before render with loaders and handle form submissions with actions.

Loaders & Actions (Data Router API) is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Are Loaders?

In React Router v6.4+ Data Router, a loader is an async function on a route that fetches data before the route renders, replacing the useEffect fetch pattern.

Defining a Loader

Add a loader property to a route object. It receives { params, request } and returns data (or a Response).

import { createBrowserRouter } from 'react-router-dom';

async function userLoader({ params }) {
  const res = await fetch(`/api/users/${params.id}`);
  if (!res.ok) throw new Response('Not Found', { status: 404 });
  return res.json();
}

const router = createBrowserRouter([
  { path: '/users/:id', element: <UserDetail />, loader: userLoader },
]);

Reading Loader Data with useLoaderData

useLoaderData() returns whatever the loader returned. The component renders only after the loader resolves.

import { useLoaderData } from 'react-router-dom';

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

What Are Actions?

An action is an async function that handles data mutations (form submissions, deletes). It runs before the route re-renders after a form POST.

async function createUserAction({ request }) {
  const formData = await request.formData();
  const name = formData.get('name');
  await fetch('/api/users', {
    method: 'POST',
    body: JSON.stringify({ name }),
    headers: { 'Content-Type': 'application/json' },
  });
  return redirect('/users');
}

Using Form to Trigger Actions

Replace <form> with React Router's <Form>. On submit it serializes fields as FormData and calls the route's action.

import { Form } from 'react-router-dom';

function NewUser() {
  return (
    <Form method="post">
      <input name="name" />
      <button type="submit">Create</button>
    </Form>
  );
}

Returning Data from Actions

Actions can return data (not just redirect). Read it in the component with useActionData() — useful for returning validation errors.

async function loginAction({ request }) {
  const data = await request.formData();
  const errors = validate(data);
  if (errors) return errors; // returned to useActionData
  await login(data);
  return redirect('/dashboard');
}

function Login() {
  const errors = useActionData();
  return (
    <Form method="post">
      {errors?.email && <p>{errors.email}</p>}
      <input name="email" />
    </Form>
  );
}

Loading States with useNavigation

useNavigation() tells you when a loader or action is in flight so you can show spinners or disable submit buttons.

function SubmitButton() {
  const navigation = useNavigation();
  const isSubmitting = navigation.state === 'submitting';
  return (
    <button type="submit" disabled={isSubmitting}>
      {isSubmitting ? 'Saving...' : 'Save'}
    </button>
  );
}

Deferred Data with defer()

Use defer() to return slow data promises from a loader without blocking render, then unwrap them with <Await> and Suspense.

import { defer, Await } from 'react-router-dom';

async function slowLoader() {
  return defer({ fast: await getFast(), slow: getSlow() });
}

function Page() {
  const { fast, slow } = useLoaderData();
  return (
    <>
      <h1>{fast.title}</h1>
      <Suspense fallback={<p>Loading...</p>}>
        <Await resolve={slow}>{data => <Chart data={data} />}</Await>
      </Suspense>
    </>
  );
}

Revalidation After Actions

After an action completes, React Router automatically re-runs all active loaders to refresh data — no manual refetch needed.

Error Handling in Loaders

Throw a Response or any error from a loader; React Router catches it and renders the route's errorElement, accessible via useRouteError().

function ErrorPage() {
  const error = useRouteError();
  return (
    <div>
      <h1>{error.status} {error.statusText}</h1>
    </div>
  );
}

Fetchers for Non-Navigation Mutations

useFetcher() lets you call loaders or actions without navigating. Useful for inline forms, like liking a post without leaving the page.

function LikeButton({ postId }) {
  const fetcher = useFetcher();
  return (
    <fetcher.Form method="post" action={`/posts/${postId}/like`}>
      <button type="submit">Like</button>
    </fetcher.Form>
  );
}

Quick Check

Which hook reads data returned by a route's loader function?

Recap

React Router's Data API uses loaders to fetch before render and actions to handle mutations. Components read loader data via useLoaderData(), action results via useActionData(), and navigation state via useNavigation().

Frequently asked questions

Is the “Loaders & Actions (Data Router API)” lesson free?

Yes — the full text of “Loaders & Actions (Data Router API)” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Loaders & Actions (Data Router API)”?

Fetch route data before render with loaders and handle form submissions with actions. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Loaders & Actions (Data Router API)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Nested Routes & Outlet Layouts
  2. Loaders & Actions (Data Router API)
  3. Protected Routes & Auth Guards
  4. Managing State in URL Search Params
← Back to React Academy