0
0
Remixframework~5 mins

Loader functions for data fetching in Remix

Choose your learning style9 modes available
Introduction

Loader functions get data before your page shows. This helps your page load with all needed info ready.

You want to show a list of items from a server when a page opens.
You need to get user info before showing their profile page.
You want to fetch data once and use it in your page components.
You want to avoid loading spinners by having data ready on page load.
Syntax
Remix
import { json } from '@remix-run/node';

export async function loader({ params, request }) {
  // fetch or get data here
  return json(data);
}

The loader function runs on the server before the page renders.

Use json() from Remix to send data to your component.

Examples
This loader returns a simple message as JSON.
Remix
import { json } from '@remix-run/node';

export async function loader() {
  const data = { message: 'Hello from loader!' };
  return json(data);
}
This loader uses URL parameters to fetch user data.
Remix
import { json } from '@remix-run/node';

export async function loader({ params }) {
  const userId = params.userId;
  const user = await getUserFromDatabase(userId);
  return json(user);
}
Sample Program

This example shows a loader that sends a list of todos. The component uses useLoaderData to get that list and display it.

Remix
import { json } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';

export async function loader() {
  const todos = [
    { id: 1, text: 'Learn Remix' },
    { id: 2, text: 'Build a cool app' }
  ];
  return json(todos);
}

export default function Todos() {
  const todos = useLoaderData();
  return (
    <main>
      <h1>My Todos</h1>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>{todo.text}</li>
        ))}
      </ul>
    </main>
  );
}
OutputSuccess
Important Notes

Loader functions run only on the server, so you can safely fetch secrets or databases.

Use useLoaderData() hook in your component to access the loader's data.

If the loader throws an error, Remix shows an error page automatically.

Summary

Loader functions fetch data before the page shows.

They run on the server and send data as JSON.

Use useLoaderData() in your component to get that data.