useLoaderData

This documentation will guide you through the usage of the useLoaderData hook provided by the @remix-run/react library. This hook allows you to access the data fetched by the loader function in your Remix components.

Usage

To use the useLoaderData hook, follow these steps:

  1. Import the useLoaderData hook from the @remix-run/react package.

  2. Define a loader function in your route module to fetch data.

  3. Use the useLoaderData hook inside your component to access the fetched data.

Example

In this example, we'll create a simple component that fetches and displays a list of users.

1. Define the loader function

In your route module file (e.g., routes/users.tsx), define the loader function that fetches data from an API:

// routes/users.tsx
import { LoaderFunction } from "@remix-run/core";

export const loader: LoaderFunction = async () => {
  const response = await fetch("https://jsonplaceholder.typicode.com/users");
  const users = await response.json();

  return users;
};

2. Use the useLoaderData hook

Now, import the useLoaderData hook and use it inside your component to access the fetched data:

// routes/users.tsx
import * as React from "react";
import { useLoaderData } from "@remix-run/react";
import { LoaderFunction } from "@remix-run/core";

export const loader: LoaderFunction = async () => {
  const response = await fetch("https://jsonplaceholder.typicode.com/users");
  const users = await response.json();
  
  return users;
};

type User = {
  id: number;
  name: string;
  email: string;
};

export default function Users() {
  const users: User[] = useLoaderData();

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            {user.name} - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

That's it! Now, the Users component will fetch and display a list of users using the useLoaderData hook.

Conclusion

The useLoaderData hook from the @remix-run/react library makes it easy to access data fetched by the loader function in your Remix components. By following the steps and examples provided in this documentation, you can quickly implement data fetching and rendering in your Remix applications.

Last updated