Blog>
Snippets

Loading Data with `loader` Functions

Use `loader` functions within the new App Router feature to fetch external data and provide it as props to your Next.js pages before they render.
import { json } from 'stream/consumers';
import { fetchPosts } from '../lib/api';

export async function loader() {
  const posts = await fetchPosts();
  return json({ posts });
}
This code snippet defines an asynchronous loader function that fetches posts using an API function fetchPosts. The loader function then returns the posts as JSON, which will be accessible as props on the Next.js page.
import { useLoaderData } from 'next/app';

export default function Blog() {
  const { posts } = useLoaderData();
  
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}
In a Next.js page component, we use the useLoaderData hook to access the 'posts' data provided by the loader function. This data is then rendered as a list of blog post titles.