Loaders & Actions (Data Router API)
Fetch route data before render with loaders and handle form submissions with actions.
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 },
]);All lessons in this course
- Nested Routes & Outlet Layouts
- Loaders & Actions (Data Router API)
- Protected Routes & Auth Guards
- Managing State in URL Search Params