How to Use Route Loader in React Router: Simple Guide
In React Router, use a
loader function inside your route configuration to fetch data before rendering a component. The loader runs when the route matches and passes its result to the component via useLoaderData() hook.Syntax
The loader is a function you add to a route object in your router setup. It runs before the component renders and returns data that the component can use.
Key parts:
loader: async () => data- fetches or prepares data.useLoaderData()- hook inside the component to access the loader's returned data.- Routes are defined with
createBrowserRouterorcreateRoutesFromElements.
javascript
import { createBrowserRouter, RouterProvider, useLoaderData } from 'react-router-dom'; const router = createBrowserRouter([ { path: '/example', loader: async () => { // fetch or prepare data return { message: 'Hello from loader' }; }, element: <ExampleComponent /> } ]); function ExampleComponent() { const data = useLoaderData(); return <div>{data.message}</div>; } export default function App() { return <RouterProvider router={router} />; }
Example
This example shows a route with a loader that fetches a random joke from an API before rendering. The component displays the joke text using useLoaderData().
javascript
import React from 'react'; import { createBrowserRouter, RouterProvider, useLoaderData } from 'react-router-dom'; // Loader fetches a joke from an API async function jokeLoader() { const response = await fetch('https://official-joke-api.appspot.com/random_joke'); if (!response.ok) throw new Error('Failed to load joke'); return response.json(); } // Component uses loader data function Joke() { const joke = useLoaderData(); return ( <div> <h2>Random Joke</h2> <p><strong>{joke.setup}</strong></p> <p>{joke.punchline}</p> </div> ); } const router = createBrowserRouter([ { path: '/', loader: jokeLoader, element: <Joke /> } ]); export default function App() { return <RouterProvider router={router} />; }
Output
<h2>Random Joke</h2>
<p><strong>Why did the scarecrow win an award?</strong></p>
<p>Because he was outstanding in his field!</p>
Common Pitfalls
- Not returning data from the loader or returning undefined causes
useLoaderData()to fail. - Forgetting to handle errors in the loader can crash the app; use try/catch or errorElement routes.
- Using loaders only works with React Router v6.4+; older versions do not support this pattern.
- Loader functions must be async or return a promise; synchronous functions returning data directly may cause issues.
javascript
/* Wrong: Loader does not return data */ const wrongLoader = async () => { return fetch('https://api.example.com/data'); // forgot to return }; /* Right: Return the fetched data */ const rightLoader = async () => { const res = await fetch('https://api.example.com/data'); return res.json(); };
Quick Reference
Route Loader Cheat Sheet:
| Concept | Description |
|---|---|
| loader | Async function in route to fetch data before render |
| useLoaderData() | Hook to access loader data inside component |
| RouterProvider | Component that applies the router with loaders |
| Error Handling | Use errorElement or try/catch in loader |
| Concept | Description |
|---|---|
| loader | Async function in route to fetch data before render |
| useLoaderData() | Hook to access loader data inside component |
| RouterProvider | Component that applies the router with loaders |
| Error Handling | Use errorElement or try/catch in loader |
Key Takeaways
Use the loader function in route config to fetch data before rendering.
Access loader data inside components with useLoaderData() hook.
Always return data or a promise from the loader function.
Handle errors in loaders to avoid app crashes.
Route loaders require React Router v6.4 or newer.