Skip to main content

Lesson 7 of 10

Data Loading - Loaders & Actions

React Router 6.4+ introduced a powerful data layer: loaders fetch data BEFORE a route renders (parallel, waterfall-free), and actions handle form mutations. This is the closest React gets to Next.js's server-side patterns while staying entirely client-side.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Loaders & Actions Pattern

Loaders & Actions Pattern
import {
  createBrowserRouter,
  RouterProvider,
  useLoaderData,
  Form,
  redirect,
  type LoaderFunctionArgs,
  type ActionFunctionArgs,
} from 'react-router-dom';

// 1. Define loader - fetches data BEFORE route renders
async function productLoader({ params }: LoaderFunctionArgs) {
  const product = await fetchProduct(params.productId!);
  if (!product) throw new Response('Not Found', { status: 404 });
  return { product }; // returned data available via useLoaderData()
}

// 2. Define action - handles form submission mutations
async function addToCartAction({ request }: ActionFunctionArgs) {
  const formData = await request.formData();
  const productId = formData.get('productId') as string;
  const quantity = Number(formData.get('quantity'));

  await addToCart({ productId, quantity });
  return redirect('/cart'); // redirect after mutation
}

// 3. Route component - data already loaded, no loading state needed
function ProductDetail() {
  const { product } = useLoaderData() as { product: Product };

  return (
    <>
      <h1>{product.name}</h1>
      <p>{product.price}</p>

      {/* React Router Form - calls the action on submit */}
      <Form method="post">
        <input type="hidden" name="productId" value={product.id} />
        <input type="number" name="quantity" defaultValue={1} min={1} />
        <button type="submit">Add to Cart</button>
      </Form>
    </>
  );
}

// 4. Router setup with createBrowserRouter (required for data APIs)
const router = createBrowserRouter([
  {
    path: '/',
    element: <RootLayout />,
    children: [
      { index: true, element: <HomePage /> },
      {
        path: 'products/:productId',
        element: <ProductDetail />,
        loader: productLoader,     // ← runs before render
        action: addToCartAction,   // ← runs on form submit
        errorElement: <ProductError />,
      },
    ],
  },
]);

// main.tsx
<RouterProvider router={router} />

// Parallel loaders - multiple async operations simultaneously
const router = createBrowserRouter([
  {
    path: 'dashboard',
    element: <Dashboard />,
    loader: async () => {
      // Both fetch in parallel - no waterfall
      const [user, stats, notifications] = await Promise.all([
        fetchUser(), fetchStats(), fetchNotifications()
      ]);
      return { user, stats, notifications };
    },
  },
]);

Tip

Tip

Practice Data Loading Loaders Actions in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and flow for Data Loading - Loaders & Actions

Practice Task

Note

Practice Task - (1) Write a working example of Data Loading Loaders Actions from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Data Loading Loaders Actions is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/10 done