| 1 | ---
|
| 2 | title: Data Loading
|
| 3 | order: 4
|
| 4 | ---
|
| 5 |
|
| 6 | # Data Loading
|
| 7 |
|
| 8 | [MODES: data]
|
| 9 |
|
| 10 | ## Providing Data
|
| 11 |
|
| 12 | Data is provided to route components from route loaders:
|
| 13 |
|
| 14 | ```tsx
|
| 15 | createBrowserRouter([
|
| 16 | {
|
| 17 | path: "/",
|
| 18 | loader: async () => {
|
| 19 | // return data from here
|
| 20 | return { records: await getSomeRecords() };
|
| 21 | },
|
| 22 | Component: MyRoute,
|
| 23 | },
|
| 24 | ]);
|
| 25 | ```
|
| 26 |
|
| 27 | ## Accessing Data
|
| 28 |
|
| 29 | The data is available in route components with `useLoaderData`.
|
| 30 |
|
| 31 | ```tsx
|
| 32 | import { useLoaderData } from "react-router";
|
| 33 |
|
| 34 | function MyRoute() {
|
| 35 | const { records } = useLoaderData();
|
| 36 | return <div>{records.length}</div>;
|
| 37 | }
|
| 38 | ```
|
| 39 |
|
| 40 | As the user navigates between routes, the loaders are called before the route component is rendered.
|
| 41 |
|
| 42 | ---
|
| 43 |
|
| 44 | Next: [Actions](./actions)
|